main.js (1960B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2021 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isString = require( '@stdlib/assert/is-string' ).isPrimitive; 24 var uppercase = require( './../../uppercase' ); 25 var replace = require( './../../replace' ); 26 var format = require( './../../format' ); 27 var trim = require( './../../trim' ); 28 29 30 // VARIABLES // 31 32 var RE_WHITESPACE = /\s+/g; 33 var RE_SPECIAL = /[!"'(),–.:;<>?`{}|~\/\\\[\]_#$*&^@%]+/g; // eslint-disable-line no-useless-escape 34 var RE_CAMEL = /([a-z0-9])([A-Z])/g; 35 36 37 // MAIN // 38 39 /** 40 * Converts a string to constant case. 41 * 42 * @param {string} str - string to convert 43 * @throws {TypeError} must provide a string primitive 44 * @returns {string} constant-cased string 45 * 46 * @example 47 * var str = constantcase( 'beep' ); 48 * // returns 'BEEP' 49 * 50 * @example 51 * var str = constantcase( 'beep boop' ); 52 * // returns 'BEEP_BOOP' 53 * 54 * @example 55 * var str = constantcase( 'isMobile' ); 56 * // returns 'IS_MOBILE' 57 * 58 * @example 59 * var str = constantcase( 'Hello World!' ); 60 * // returns 'HELLO_WORLD' 61 */ 62 function constantcase( str ) { 63 if ( !isString( str ) ) { 64 throw new TypeError( format( 'invalid argument. Must provide a string. Value: `%s`.', str ) ); 65 } 66 str = replace( str, RE_SPECIAL, ' ' ); 67 str = replace( str, RE_CAMEL, '$1 $2' ); 68 str = trim( str ); 69 str = replace( str, RE_WHITESPACE, '_' ); 70 return uppercase( str ); 71 } 72 73 74 // EXPORTS // 75 76 module.exports = constantcase;