I’m looking to match /(?=\W)(gimme)(?=\W)/gi or alike. The \W are supposed to be zero-width characters to surround my actual match.
Maybe some background. I want te replace certain words (always \w+) with some literal padding added, but only if it’s not surrounded by a \w. (That does sound like a negative lookaround, but I hear JS doesn’t do those!?)
(Btw: the above “gimme” is the word literal I want to replace. If that wasn’t obvious.)
It has to be (?) a lookaround, because the \W have to be zero-width, because the intention is a .replace(...) and I cannot replace/copy the surrounding characters.
So this won’t work:
text.replace(/(?=\W)(gimme)(?=\W)/gi, function(l, match, r) {
return l + doMagic(match) + r;
})
The zero-width chars have to be ignored, so the function can return (and replace) only doMagic(match).
I have only very limited lookaround experience and non of it in JS. Grazie.
PS. Or maybe I need a lookbehind and those aren’t supported in JS..? I’m confused?
PS. A little bit of context: http://jsfiddle.net/rudiedirkx/kMs2N/show/ (ooh a link!)
you can use word boundary shortcut
\bto assert that it’s the whole word that you are matching.The easiest way to achieve what you want to do is probably to match:
/(\s+gimme)(?=\W)/giand replace with
[yourReplacement]– i.e. capture the whitespaces before ‘gimme’ and then include one in the replacement.gimmeliteral and then using the groups with backreference:(\W+?)gimme(\W+?)– your match – note that this time the before and after characters are in the capturing groups 1 and 2And you’d want to use
\1[yourReplacement]\2as replacement string – not sure how you use backreference in JS, but the idea is to tell the engine that with\1you mean whatever was matched by the first captuing parenthesis. In some languages these are accessed with$1.