main.js (2483B)
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 capitalize = require( './../../capitalize' ); 25 var lowercase = require( './../../lowercase' ); 26 var replace = require( './../../replace' ); 27 var format = require( './../../format' ); 28 var trim = require( './../../trim' ); 29 30 31 // VARIABLES // 32 33 var RE_WHITESPACE = /\s+/g; 34 var RE_SPECIAL = /[-!"'(),–.:;<>?`{}|~\/\\\[\]_#$*&^@%]+/g; // eslint-disable-line no-useless-escape 35 var RE_TO_CAMEL = /(?:\s|^)([^\s]+)(?=\s|$)/g; 36 var RE_CAMEL = /([a-z0-9])([A-Z])/g; 37 38 39 // FUNCTIONS // 40 41 /** 42 * Converts first capture group to uppercase. 43 * 44 * @private 45 * @param {string} match - entire match 46 * @param {string} p1 - first capture group 47 * @param {number} offset - offset of the matched substring in entire string 48 * @returns {string} uppercased capture group 49 */ 50 function replacer( match, p1, offset ) { 51 p1 = lowercase( p1 ); 52 return ( offset === 0 ) ? p1 : capitalize( p1 ); 53 } 54 55 56 // MAIN // 57 58 /** 59 * Converts a string to camel case. 60 * 61 * @param {string} str - string to convert 62 * @throws {TypeError} must provide a string primitive 63 * @returns {string} camel-cased string 64 * 65 * @example 66 * var out = camelcase( 'foo bar' ); 67 * // returns 'fooBar' 68 * 69 * @example 70 * var out = camelcase( 'IS_MOBILE' ); 71 * // returns 'isMobile' 72 * 73 * @example 74 * var out = camelcase( 'Hello World!' ); 75 * // returns 'helloWorld' 76 * 77 * @example 78 * var out = camelcase( '--foo-bar--' ); 79 * // returns 'fooBar' 80 */ 81 function camelcase( str ) { 82 if ( !isString( str ) ) { 83 throw new TypeError( format( 'invalid argument. First argument must be a string. Value: `%s`.', str ) ); 84 } 85 str = replace( str, RE_SPECIAL, ' ' ); 86 str = replace( str, RE_WHITESPACE, ' ' ); 87 str = replace( str, RE_CAMEL, '$1 $2' ); 88 str = trim( str ); 89 str = replace( str, RE_TO_CAMEL, replacer ); 90 return str; 91 } 92 93 94 // EXPORTS // 95 96 module.exports = camelcase;