;

How to Convert String to Camel Case in Javascript


Tutorialsrack 27/02/2022 Jquery Javascript

In this article, you’ll learn how to convert string to camel case in Javascript. To convert the string to camel, you can use the Regex.

Let's take a look at an example:

function camelCase(text) {
    text = text.toLowerCase().replace(/[-_?:*%!;¿\s.]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
    return text.substr(0, 1).toLowerCase() + text.substr(1);
}

console.log(camelCase('is camel case'));
// output==> "isCamelCase"

console.log(camelCase('Hello TUTORIALSRack'));
// output==> "helloTutorialsrack"

console.log(camelCase('Hello-TUTORIALS_Rack'));
// output==> "helloTutorialsRack"

console.log(camelCase('!WELcome--to.¿?*_TUTORIALS-%___Rack'));
// output==> "welcomeToTutorialsRack"

Here is another example to convert string to camelcase

function camelCase(text) {
  return `${text}`
    .replace(new RegExp(/[-_]+/, 'g'), ' ')
    .replace(new RegExp(/[^\w\s]/, 'g'), '')
    .replace(
      new RegExp(/\s+(.)(\w+)/, 'g'),
      ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`
    )
    .replace(new RegExp(/\s/, 'g'), '')
    .replace(new RegExp(/\w/), s => s.toLowerCase());
}

console.log(camelCase('is camel case'));
// output==> "isCamelCase"

console.log(camelCase('Hello TUTORIALSRack'));
// output==> "helloTutorialsrack"

console.log(camelCase('Hello-TUTORIALS_Rack'));
// output==> "helloTutorialsRack"

console.log(camelCase('!WELcome--to.¿?*_TUTORIALS-%___Rack'));
// output==> "welcomeToTutorialsRack"

Here is another example to convert string to camelCase:

function camelCase(str) {
    return str
        .toLowerCase()
        .replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase())
        .replace(/^\w/, (c) => c.toLowerCase());
}
console.log(camelCase('is camel case'));
// output==> "isCamelCase"

console.log(camelCase('Hello TUTORIALSRack'));
// output==> "helloTutorialsrack"

console.log(camelCase('Hello-TUTORIALS_Rack'));
// output==> "helloTutorialsRack"

console.log(camelCase('!WELcome--to.¿?*_TUTORIALS-%___Rack'));
// output==> "welcomeToTutorialsRack"

I hope this article will help you to understand how to convert string to camel case in Javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags