main.js (2050B)
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 lowercase = require( './../../lowercase' ); 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 kebab case. 41 * 42 * @param {string} str - string to convert 43 * @throws {TypeError} must provide a string primitive 44 * @returns {string} kebab-cased string 45 * 46 * @example 47 * var str = kebabCase( 'Hello World!' ); 48 * // returns 'hello-world' 49 * 50 * @example 51 * var str = kebabCase( 'foo bar' ); 52 * // returns 'foo-bar' 53 * 54 * @example 55 * var str = kebabCase( 'I am a tiny little teapot' ); 56 * // returns 'i-am-a-tiny-little-teapot' 57 * 58 * @example 59 * var str = kebabCase( 'BEEP boop' ); 60 * // returns 'beep-boop' 61 * 62 * @example 63 * var str = kebabCase( 'isMobile' ); 64 * // returns 'is-mobile' 65 */ 66 function kebabCase( str ) { 67 if ( !isString( str ) ) { 68 throw new TypeError( format( 'invalid argument. Must provide a string. Value: `%s`.', str ) ); 69 } 70 str = replace( str, RE_SPECIAL, ' ' ); 71 str = replace( str, RE_CAMEL, '$1 $2' ); 72 str = trim( str ); 73 str = replace( str, RE_WHITESPACE, '-' ); 74 return lowercase( str ); 75 } 76 77 78 // EXPORTS // 79 80 module.exports = kebabCase;