Don't replace regex if it is enclosed by a character

javascript, jquery, regex

Solution

That's a tricky sort of thing to do with regular expressions. I think what I'd do is something like this:

var msg = source.replace(/(-[^-]+-|\*[^*]+\*)/g, function(_, grp) {
  return grp[0] === '-' ? grp.replace(/^-(.*)-$/, "~$1~") : grp;
});

jsFiddle Demo

That looks for either `-` or `*` groups, and only performs the replacement on dashed ones. In general, "nesting" syntaxes are challenging (or impossible) with regular expressions. (And of course as a comment on the question notes, there are special cases — dangling metacharacters — that complicate this too.)

Problem

I would like to replace all strings that are enclosed by `-` into strings enclosed by `~`, but not if this string again is enclosed by `*`. As an example, this string... ``` The -quick- *brown -f-ox* jumps. ``` ...should become... ``` The ~quick~ *brown -f-ox* jumps. ``` We see `-` is only replaced if it is not within `*<here>*`. My javascript-regex for now (which takes no care whether it is enclosed by `*` or not): ``` var message = source.replace(/-(.[^-]+?)-/g, "~$1~"); ``` Edit: Note that it might be the case that there is an odd number of `*`s.

Original source

Related problems