Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RegExp match and replace to it's uppercase in javascript

I have a sentence with a colon in the middle, and want to capitalize the first word after the colon, I would like to know how to replace the matching letter with its’ upper case using regexp in javascript, however xx.replace(/(:\s\w)/, '$1'.toUpperCase()) doesn’t work, it returns Lactobacillus strains: a BIOPEP-UWM database-based analysis. Expect Lactobacillus strains: A BIOPEP-UWM database-based analysis.

MWE:

var xx = 'Lactobacillus strains: a BIOPEP-UWM database-based analysis';
xx.replace(/(:\s\w)/, '$1'.toUpperCase());

Any suggestion is appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

All you need to do is use a callback function as the second argument instead of '$1'

var xx = 'Lactobacillus strains: a BIOPEP-UWM database-based analysis';
console.log(xx.replace(/:\s\w/, fullMatch => fullMatch.toUpperCase()));

What you were doing was capitalizing the literal value '$1', which is the same, so it was just passing '$1' into the replace function

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading