13

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

5
  • "UPPERCASE part" ?? which are the delimiters? Commented Aug 27, 2015 at 18:31
  • Do you have any parameters that define what should be ignored/not ignored? Commented Aug 27, 2015 at 18:31
  • Why should It's August I be ignored? Is there any hidden requirements there? Like, the first word of the sentence should be preserved, the month names,.... Commented Aug 27, 2015 at 18:31
  • 1
    What if your input is It's HTML? Commented Aug 27, 2015 at 18:36
  • Why use RegEx for this? its as simple as value.toLowerCase() Commented Aug 27, 2015 at 18:37

2 Answers 2

34

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
Sign up to request clarification or add additional context in comments.

1 Comment

Any chance the replacement from upper-case to lower-case can be done by the regex engine itself?
5

A solution without regex:

function isUpperCase(str) {
        return str === str.toUpperCase();
    }

var str = "It's around August AND THEN I get an email";
var matched = str.split(' ').map(function(val){
  if (isUpperCase(val) && val.length>1) {
    return val.toLowerCase();
    }
  return val;        
});

console.log(matched.join(' '));

1 Comment

Cool, this solution is useful for another problem I had, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.