Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
RegExp javascript替换所有不工作_Javascript_Regex_Replace - Fatal编程技术网

RegExp javascript替换所有不工作

RegExp javascript替换所有不工作,javascript,regex,replace,Javascript,Regex,Replace,我把这个代码弄糊涂了 <!DOCTYPE html> <html> <body> <p>Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:</p> <p id="demo">Microsoft Visit Microsoft! Microsoft vi

我把这个代码弄糊涂了

<!DOCTYPE html>
<html>

    <body>
        <p>Click the button to replace "Microsoft" with "W3Schools" in the paragraph
            below:</p>
        <p id="demo">Microsoft Visit Microsoft! Microsoft visit visit microsoft Visit Visit
            Visit Visit</p>
        <button onclick="myFunction()">Try it</button>
        <script>
            function myFunction() {
                document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML.replace(/ Visit |Microsoft/gi, ' test ');
            }
        </script>
    </body>

</html>
第二次点击后

test test test ! test test test test test test test test 
为什么有些词在第一时间没有改变?
真诚地

发生这种情况是因为在您的
#演示
内容中有两个未被替换的
访问
单词后面没有空格(第一个有新行,第二个有行尾)

为了修复它,您可以使用
\b
作为:
/\bVisit\b | Microsoft/gi


演示:

这是因为正则表达式中的
访问
周围有空格:

 / Visit /
这就需要在“访问”一词的两侧留出一个空格。正则表达式匹配不会重叠,所以如果您有

  Visit Visit Visit Visit
…那么每个“访问”实例之间的两个空格只能属于一个匹配。因此您的正则表达式匹配将如下所示(使用
{
显示匹配开始的位置,使用
}
显示匹配结束的位置):

在“访问”之间用两个空格试试。你会看到它把他们都吸引住了


编辑:愿景战胜了我;如果你只想匹配单词,他建议使用
\b
是完美的。

/Visit | Microsoft/gi
的意思很简单

  • 查找“访问”(周围有空格)
  • |
    (或)
  • 查找“Microsoft”
  • g
    标志-查找所有匹配项
  • i
    标志-进行不区分大小写的搜索

你到底想做什么?RegEx?@Сааааааааа是的,我开发了一个工具栏并向页面注入了一些东西。我想搜索单词,\b对我来说是个不错的选择。尽管你的解决方案有效,但问题不是由新行和行尾引起的,而是由Justin Morgan在回答中提到的。如果线路末端出现问题,那么第二次单击如何替换该访问?如果我在JSFIDLE中使用OP的原始正则表达式,那么第二次单击不会替换最后两次访问。因此,我认为OP的html可能在新的和结束行之前的访问周围有一些空格。
  Visit Visit Visit Visit
 { Visit }Visit{ Visit }Visit