Search code examples
javascriptregexfunctionuppercaseapostrophe

Regex to Upper Case all words but exclude ' (apostrophe)


I'm trying to build a funct to UpperCase all the string words but I'm having a problem with the following:

String.prototype.upper = function() {
    return this.replace(/[^a-zA-Z0-9]+(.)/g, chr => chr.toUpperCase())
 }


let str = "My uncle's car is red";
console.log(str.upper()) 


//My Uncle'S Car Is Red

I need to exclude the S from being UpperCased, after the apostrophe.

Any ideas how this can be done?

Thank you


Solution

  • I would change the Regex to \s+\w to search for a letter after spaces and/or tabs.

    const upper = (input) => input.replace(/\s+\w/g, x => x.toUpperCase());
    console.log(upper("My uncle's car is red"));