我想用javascript中的另一个单词替换字符串的第N个单词。例如:
<div id="sentence">This is some sentence that has the word is.</div>
将此句的第二个单词is
替换为was
,最后保留is
。我认为以下内容可行,但事实并非如此:
var p = new RegExp('(?:\\S+ ){1}(\\S+)');
$("#sentence").html(function(k,v) {return v.replace(p, "was");});
答案 0 :(得分:2)
使用捕获组并使用$1
var p = new RegExp('^((\\S+ ){1})(\\S+)');
$("#sentence").html(function(k,v) {return v.replace(p, "$1was");});
完整示例:
<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
</head>
<body>
<div id="sentence">This is some sentence that has the word is.</div>
<script>
var p = new RegExp('^((\\S+ ){1})(\\S+)');
$("#sentence").html(function(k,v) {return v.replace(p, "$1was");});
</script>
</body>
</html>
说明:
^
匹配字符串的开头。
(\\S+ ){n}
重复n次,但这也会重复捕获。 (仅保留最后一组。)
((\\S+ ){1})
将重复内容嵌入捕获组。 $1
(\\S+ ){1}
这是第二个捕获组。 $2
只有最后一次迭代存储在$2
(\\S+)
捕获要替换的额外单词。 $3
v.replace(p, "$1was");
$ 1将第一个捕获组添加回字符串。第二个捕获组被排除在外。