Javascript .replace() 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19575604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:01:15  来源:igfitidea点击:

Javascript .replace() not working

javascriptreplace

提问by Hoser

carList = cars.innerHTML;
alert(carList);
carList = carList.replace("<center>","").replace("</center>","").replace("<b>","").replace("</b>","");
alert(carList);

enter image description here

在此处输入图片说明

Why in the world is this happening? I've tried splitting this out into individual string.replace()'s and that gives the same result.

为什么会发生这种情况?我尝试将其拆分为单独的 string.replace() 并给出相同的结果。

回答by Karl-Johan Sj?gren

Using .replace()with a string will only fix the first occurrence which is what you are seeing. If you do it with a regular expression instead you can specify that it should be global (by specifying it with a gafterwards) and thus take all occurrences.

.replace()与字符串一起使用只会修复您所看到的第一次出现。如果您使用正则表达式执行此操作,则可以指定它应该是全局的(通过使用 after 指定它g),从而获取所有出现的次数。

carList = "<center>blabla</center> <b>some bold stuff</b> <b>some other bold stuff</b>";
alert(carList);
carList = carList.replace(/<center>/g,"").replace(/<\/center>/g,"").replace(/<b>/g,"").replace(/<\/b>/g,"");
alert(carList);

See this fiddlefor a working sample.

有关工作示例,请参阅此小提琴

回答by r3mainer

You can use a regular expression to match all of these at the same time:

您可以使用正则表达式同时匹配所有这些:

carList = carList.replace(/<\/?(b|center)>/g,"");

The gflag at the end of the match string tells Javascript to replace all occurrences, not just the first one.

g匹配字符串末尾的标志告诉 Javascript 替换所有匹配项,而不仅仅是第一个。