带有捕获括号的JavaScript正则表达式 [英] JavaScript regular expression with capturing parentheses

查看:112
本文介绍了带有捕获括号的JavaScript正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这一段:

<p>FIRST SECOND THIRD</p>

我希望在SPAN中包装第二个单词,如下所示:

and I want to wrap the second word in a SPAN like so:

<p>FIRST <span>SECOND</span> THIRD</p>

如果我这样做:

text.replace(/\s(\w+)\s/, '<span>$1</span>');

单词之前和之后的空格字符消失。为什么?我究竟做错了什么?我想 / \((\ w +)\ s / 捕获单词而不是空格。

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.

见这里: 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.

如果JavaScript支持前瞻和后瞻断言,你可以这样做:

If JavaScript supported both lookahead and lookbehind assertions you could do this:

text.replace(/(?<\s)(\w+)(?=\s)/, '<span>$1</span>');

但它没有,所以你可以尝试捕捉空格(与你的单词分开)包装)并将它们放回去:

But it doesn't, so you can try capturing the spaces (separately from the word you're wrapping) and putting them back in instead:

text.replace(/(\s)(\w+)(\s)/, '$1<span>$2</span>$3');

这篇关于带有捕获括号的JavaScript正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆