javascript:正则表达式匹配未包含在自定义标签中的单词

标签 javascript regex

我需要匹配并替换字符串中未包含在标签 :$$: 内的所有出现的“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/

相关文章:

javascript - 如何将焦点设置到ui :repeat JSF中的最后一项

javascript - 如何防止在输入字段中写入和粘贴特殊字符?

javascript - 对象 HTMLInputElement attr 不是函数

javascript - 自定义表单验证表单

javascript - JavaScript 中有 RegExp.escape 函数吗?

php - 删除删除线的 unicode 文本?

javascript - HTML 中的正则表达式或

javascript - 如何在javascript中将字符串值作为引用传递并在那里进行更改

java - 正则表达式检测实体的 "more than one"

regex - BASH shell 使用正则表达式从文件中获取值到参数中