Search code examples
javascriptregexstringquotes

Replace string everywhere except if its within quotes


I would like to replace all :) by :D, except if they are within quotes "

Example 1:

Hey man :D, how're you? :) My friend told me "this can't be true :)"

becomes

Hey man :D, how're you? :D My friend told me "this can't be true :)"

As you see, :) is not replaced if it's enclosed by ". If this condition wouldn't be there, it would be quite simple, right? I am using Javascript (jQuery) for all this.

If this is not plainly possible with a regex, what would be an alternate suggestion?


Solution

  • Assuming no double quote is unbalanced, this is the regex that should work for you:

    :\)(?=(?:(?:[^"]*"){2})*[^"]*$)
    

    Explanation: This regex is using a positive lookahead that basically is matching 0 or more occurrences of a pair of some text until a double quote is found i.e. ([^"]*"){2} on the right hand side (RHS) of every match of :).

    Which in simple term means replace a :) only if it is outside double quotes since all the matches inside double quotes will have odd number of [^"]*" matches on RHS.

    Live Demo: 1. http://www.rubular.com/r/3aixZy5bYR

    Live Demo: 2. http://ideone.com/C679NW