I’m attempting to replace certain parts of a string with regex in JavaScript, but only if they are not wrapped within {{{ and }}}.
The system I currently have in place does multiple string replacements and wraps the replacements in these brackets. So therefore, if I was to replace “h” with the day of the week (let’s say Thursday), the replacement would output "{{{Thursday}}}". If the replacement was to happen again, the string would ultimately become "{{{T{{{Thursday}}}ursday}}}" as the “h” in Thursday has been replaced.
What I’m looking for is a regex pattern that would replace the “h” but only if it is not contained within the {{{ and }}} wrappers.
Thanks in advance 🙂
Edit:
Here is some example code. Each replacement gets wrapped in the brackets, and regex patterns use (?!{{{) and (?!}}}) in an attempt to avoid past replacements.
var string = 'n d m y',
dayTextRegex = /(?!{{{)n(?!}}})/g,
dayRegex = /(?!{{{)d(?!}}})/g,
monthRegex = /(?!{{{)m(?!}}})/g,
yearRegex = /(?!{{{)y(?!}}})/g;
string = string.replace(dayTextRegex, '{{{Monday}}}');
string = string.replace(dayRegex, '{{{04}}}');
string = string.replace(monthRegex, '{{{June}}}');
string = string.replace(yearRegex, '{{{2012}}}');
//string is now equal to "{{{Mon{{{04}}}ay}}} {{{04}}} {{{June}}} {{{2012}}}"
Update
Just realized this won’t work, but leaving it here for now until I can figure it out. It’s interesting nonetheless 🙂
Mimicking the lookbehind and lookforward assertions in regex:
Returns:
See also: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
Update 2
Seeing how you’re using the expressions, I would use this construct instead:
Output:
This basically performs replacement without overlaps, so you don’t have to worry about previously braced expressions.