regex - JavaScript regular expression with capturing parentheses -
i have paragraph:
<p>first second third</p>
and want wrap second word in span so:
<p>first <span>second</span> third</p>
if this:
text.replace(/\s(\w+)\s/, '<span>$1</span>');
the space characters before , after word disappear. why? doing wrong? thought /\s(\w+)\s/
captures word not spaces.
see here: http://jsfiddle.net/simevidas/tptzv/
the spaces stripped away because they're part of entire match. capture remembers substitute replacement string via backreferences.
if javascript supported both lookahead , lookbehind assertions this:
text.replace(/(?<\s)(\w+)(?=\s)/, '<span>$1</span>');
but doesn't, can try capturing spaces (separately word you're wrapping) , putting them in instead:
text.replace(/(\s)(\w+)(\s)/, '$1<span>$2</span>$3');
Comments
Post a Comment