Proper case a string using RegEx in Javascript, except for words in parenthesis


Today I had to find a way to proper case a string, except anything that is in parenthesis.  That sounds like a mouthful, so to clarify, I wanted to turn “JAVASCRIPT ROCKS (JS)” into “Javascript Rocks (JS)”, so I created a regular expression to do this task in an Adobe LiveCycle form.

this.rawValue = this.rawValue.replace(/(?!\w*\))(\w\S*)/g, 
  function(txt){
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}
  );

I learned that this uses a negative lookahead that looks for things in parenthesis, and if it is in parenthesis, it does not match the next part, which is looking for words followed by white space.

Have fun using negative lookaheads in RegEx.  This doesn’t have to only be done in Javascript, but can be done in most any language.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.