I have this paragraph:
<p>FIRST SECOND THIRD</p>
and I want to wrap the second word in a SPAN like so:
<p>FIRST <span>SECOND</span> THIRD</p>
If I do this:
text.replace(/\s(\w+)\s/, '<span>$1</span>');
the space characters before and after the word disappear. Why? What am I doing wrong? I thought /\s(\w+)\s/ captures the word but not the spaces.
See here: http://jsfiddle.net/simevidas/TpTzV/
The spaces are stripped away because they’re part of the entire match. The capture is what it remembers to substitute back into the replacement string via backreferences.
If JavaScript supported both lookahead and lookbehind assertions you could do this:
But it doesn’t, so you can try capturing the spaces (separately from the word you’re wrapping) and putting them back in instead: