0
votes

I am trying to use .replace() on a string to omit an underscore and camel case whatever string is passed through the function. I was able to get a " " and "-" omitted but am struggling using \W/ to omit a "_".

The small piece of code I have written is:

function toCamelCase(str) {
  return str.replace(/\W+(.)/g, function(match, chr) {
    return chr.toUpperCase();
  });
}

console.log(toCamelCase("javaScript Exercises"));
console.log(toCamelCase("java-script-exercises"));
console.log(toCamelCase("java_script_exercises"))

I have it even so if the first letter is entered capital it remains capital and only runs camel case after.

If you are able to run the code snippet you will see the output:

javaScriptExercises
javaScriptExercises
java_script_exercises //my issue is here

I have seen a couple errors saying chr.upperCase() is not a function in trying different versions of /\W+(.)/g throughout the project. Is this not doable with .replace()?

2

2 Answers

1
votes

Try this. As \W contains _ in the list and it will not replace _.

\W is same as [^a-zA-Z0-9_]

function toCamelCase(str){
    return str.replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr) {
      return chr.toUpperCase();
    });
  }
  console.log(toCamelCase("javaScript Exercises"));
  console.log(toCamelCase("java-script-exercises"));
  console.log(toCamelCase("java_script_exercises"))
0
votes

Instead of \W+, use [\W_]+ - underscores are word characters, so [\W_] will match anything which is a non-word character or an underscore, and remove them:

function toCamelCase(str){
  return str.replace(/[\W_]+(.)/g, function(match, chr) {
    return chr.toUpperCase();
  });
}

console.log(toCamelCase("javaScript Exercises"));
console.log(toCamelCase("java-script-exercises"));
console.log(toCamelCase("java_script_exercises"))

Spaces and -s aren't word characters, so the \W matches them. The logic might be easier to follow if you had a whitelist of which characters needed to be replaced - eg, using a character set of [ _-]:

function toCamelCase(str){
  return str.replace(/[ _-]+(.)/g, function(match, chr) {
    return chr.toUpperCase();
  });
}

console.log(toCamelCase("javaScript Exercises"));
console.log(toCamelCase("java-script-exercises"));
console.log(toCamelCase("java_script_exercises"))