Search code examples
javascriptregexreplaceparentheses

JavaScript Regex replace words with their first letter except when within parentheses


I am looking for JavaScript Regex that will replace the words in a block of text with only the first letter of each word BUT if there are words within brackets, leave them intact with the brackets. The purpose is to create a mnemonic device for remembering lines from a screenplay or theatrical script. I want the actual lines reduced to first letters but the stage directions (in parenthesis) to be unaltered.

For example:

Test test test (test). Test (test test) test test.

Would yield the result:

T t t (test). T (test test) t t.

Using:

 .replace(/(\w)\w*/g,'$1')

Yields:

T t t (t). T (t t) t t.

My understanding of regex is very poor. I have been researching it for several days now and have tried many things but can't seem to wrap my head around a solution.


Solution

  • You can accomplish this with a small tweak to your regex:

    /(\w|\([^)]+\))\w*/
    

    The added part \([^)]+\) matches everything inside two pairs of parenthesis.

    "Test test test (test). Test (test test) test test.".replace(/(\w|\([^)]+\))\w*/g,'$1')
    >"T t t (test). T (test test) t t."
    

    Edit: to address issues raised in the comments

    "Test test test (test). Test (test. test.) test test. test(test) (test)test".replace(/(\w|\([^)]+)\w*/g,'$1')
    >"T t t (test). T (test. test.) t t. t(test) (test)t"