我想用 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");});
最佳答案
使用捕获组并将其添加到带有 $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 将第一个捕获组添加回字符串中。第二个捕获组被忽略。
关于javascript - 使用正则表达式替换 javascript 中的第 N 个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28550049/