0

I'm trying to rename a certain type of strings with .replace() and REGEX.

  • myCustomClass -> customClass
  • myCustomOption -> customOption

I need something that in effect does this string.charAt(0).toLowerCase() + string.slice(1), but with REGEX.

So I'm working on something like this

var myCustomClass = 'myCustomClass',
    myCustomOption = 'myCustomOption';
    
document.body.innerHTML = myCustomClass.replace('my','')
                         .replace(/([A-Z])/, ('$1').toLowerCase() ) + '<br>'

document.body.innerHTML += myCustomOption.replace('my','')
                          .replace(/([A-Z])/, ('$1').toLowerCase() )

The results are CustomClass and CustomOption, which is not what I was expecting. How can I do this please?

thednp
  • 4,401
  • 4
  • 33
  • 45

1 Answers1

0

As suggested, this is the solution:

string.replace(/[A-Z]/, (match) => match.toLowerCase() )

Demo:

var myCustomClass = 'myCustomClass',
    myCustomOption = 'myCustomOption';
    
document.body.innerHTML = myCustomClass.replace('my','')
                         .replace(/[A-Z]/, (match) => match.toLowerCase() ) + '<br>'

document.body.innerHTML += myCustomOption.replace('my','')
                          .replace(/[A-Z]/, (match) => match.toLowerCase() )
thednp
  • 4,401
  • 4
  • 33
  • 45