Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change uppercase to lowercase with regex javascript

It could be any string, it should match only the UPPERCASE part and change to lowercase, for example:

"It's around August AND THEN I get an email"

become

"It's around August and then I get an email"

as you can see the word It's, August and I should be ignored

like image 749
John Smith Avatar asked Aug 27 '15 18:08

John Smith


People also ask

How to change uppercase to lowercase in JavaScript?

The toLowerCase() method converts a string to lowercase letters. The toLowerCase() method does not change the original string.

How do you uppercase in regular expressions?

This can be done easily using regular expressions. In a substitute command, place \U or \L before backreferences for the desired output. Everything after \U , stopping at \E or \e , is converted to uppercase. Similarly, everything after \L , stopping at \E or \e , is converted to lowercase.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.


1 Answers

Use /\b[A-Z]{2,}\b/g to match all-caps words and then .replace() with a callback that lowercases matches.

var string = "It's around August AND THEN I get an email",
  regex = /\b[A-Z]{2,}\b/g;

var modified = string.replace(regex, function(match) {
  return match.toLowerCase();
});

console.log(modified);
// It's around August and then I get an email

Also, feel free to use a more complicated expression. This one will look for capitalized words with 1+ length with "I" as the exception (I also made one that looked at the first word of a sentence different, but that was more complicated and requires updated logic in the callback function since you still want the first letter capitalized):

\b(?!I\b)[A-Z]+\b
like image 154
Sam Avatar answered Oct 14 '22 14:10

Sam