我需要匹配并替换字符串中未包含在标签 :$
和 $:
内的所有出现的“word”。除了“word”之外,标签中可能还有其他字符。
所以,假设我有字符串
abc 单词嘿 :$ 我的单词 $:
我需要将word
替换为letter
;本质上我想获得以下字符串:
abc 字母嘿 :$ 我的话 $:
在 JavaScript 中实现这一目标的最佳方法是什么?
更多信息:
标签不会嵌套。 该字符串可以单独包含字符“:”和“$”。在这种情况下,它们应该被视为简单字符而不是标签。
最佳答案
我无法为此指定 RegExp,因此这里有一个更强制的方法来执行此操作 - http://jsfiddle.net/dNhLm/
var text = "abc word hey :$ my word $:";
var replace = function(text, pattern, replacement) {
var parts = [];
// This will split the string into parts. The ones that has :$ we will have to proceed further and ignore
var splitByEnd = text.split('$:');
for (i = 0, l = splitByEnd.length; i < l; i++) {
// Here we should have at most 2 parts. The left one will be outside of the :$,$: pairs and is the
// one we will apply the replacement. The right one if present will be between the :$,$: pairs and is
// not a subject of replacement.
var splitByStart = splitByEnd[i].split(':$');
splitByStart[0] = splitByStart[0].replace(pattern, replacement);
parts.push(splitByStart.join(':$'));
}
return parts.join('$:');
}
alert(replace(text, 'word', 'letter'));
关于javascript:正则表达式匹配未包含在自定义标签中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20998274/