Skip to content

stringToCamelCase() Helper Method

The stringToCamelCase() Helper Method module provides a helper function that converts a passed in string and returns that string formatted in camelCase.

Import

To import the stringToCamelCase() Helper Method:

javascript
import { stringToCamelCase } from '@obewds/vueventus'

Arguments

Returns: String

ArgsTypeStatusDescription
textStringRequiredString to convert into camel case format

Use Example

javascript
console.log( stringToCamelCase('test string here') )
// returns (string): 'testStringHere'

console.log( stringToCamelCase('Test String Here') )
// returns (string): 'testStringHere'

console.log( stringToCamelCase('TestString here') )
// returns (string): 'testStringHere'

console.log( stringToCamelCase('Test stringHere') )
// returns (string): 'testStringHere'

console.log( stringToCamelCase('test-string-here') )
// returns (string): 'testStringHere'

Module Code

ts
// ./src/helpers/stringToCamelCase.ts

export default function(string: string): string {

    // 1st replace everything except alphanumeric characters and whitespace with a space
    // 2nd replace collapses multiple adjacent whitespace to single spaces
    // 3rd/4th replaces converts to camel case
    return string.replace(/[^\w\s\']|_/g, " ").replace(/\s+/g, " ").replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
        return index === 0 ? word.toLowerCase() : word.toUpperCase()
    }).replace(/\s+/g, '')

}

Released under the MIT License