Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - converts dash/underscore delimited words into camel casing

Tags:

javascript

Here is a code that works for "underscore" perfectly :

   function toCamelCase(input){
      return input.toLowerCase().replace(/-(.)/g, function(match,group1)
      {
        return group1.toUpperCase();
      });
    }

But when i tried to add for either "underscore" or "hyphen" in regex,the below code is not working telling me that " Uncaught TypeError: Cannot read property 'toUpperCase' of undefined "

function toCamelCase(input){
  return input.toLowerCase().replace(/-(.)|_(.)/g, function(match,group1)
  {
    return group1.toUpperCase();
  });
}

Can anyone please tell me why it is not working and rectify the code please ?

like image 722
Arjun Kumar Avatar asked Mar 18 '26 18:03

Arjun Kumar


1 Answers

Simply change your regex to /[-_](.)/g

function toCamelCase(input) {
  return input.toLowerCase().replace(/[-_](.)/g, function(match, group1) {
    return group1.toUpperCase();
  });
}

const s = 'foo-bar_baz';
console.log(toCamelCase(s));
like image 110
baao Avatar answered Mar 20 '26 07:03

baao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!