Javascript .replace()无效 [英] Javascript .replace() not working
本文介绍了Javascript .replace()无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
carList = cars.innerHTML;
alert(carList);
carList = carList.replace("<center>","").replace("</center>","").replace("<b>","").replace("</b>","");
alert(carList);
为什么世界会发生这种情况?我已经尝试将其拆分为单独的string.replace(),并给出相同的结果。
Why in the world is this happening? I've tried splitting this out into individual string.replace()'s and that gives the same result.
推荐答案
使用带字符串的 .replace()
只会修复第一次出现就是你所看到的。如果你用正则表达式代替它,你可以指定它应该是全局的(之后用 g
指定它),因此可以全部出现。
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 g
afterwards) and thus take all occurrences.
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 fiddle for a working sample.
这篇关于Javascript .replace()无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文