使用正则表达式替换标记内的特定文本

时间:2014-10-13 19:26:33

标签: javascript html regex

我是正则表达式的新手,我不理解正则表达式的文档。我想请求如何替换JavaScript警报中的特定文本。

alert("$xx this some text")

alert("this some test $xx")

alert("this some $xx test")

<pre>
  <p>$xx - this should not be replaced this is inside a div or a p tags</p>
  <script>alert("$xx - this should be replace")</script>
</pre>

我想将$xx替换为$yyHere是我想要做的演示。

1 个答案:

答案 0 :(得分:0)

要查找类似$xx的序列,您可以使用此正则表达式:

\$xx

在JavaScript中,这可能如下所示:

var text = "$xx";
document.write("text before regex: " + text + "<br>");
document.write("text with regex:   " + text.replace(/\$xx/g, "this text was inserted by the regex") + "<br>");
document.write("text after regex:  " + text + "<br>");

当然您可以使用alert代替document.write,我只是在这里使用它,因为代码片段可以更好地证明这一点。