Javascript .replace() not working

后端 未结 2 1172
[愿得一人]
[愿得一人] 2021-01-11 11:58
carList = cars.innerHTML;
alert(carList);
carList = carList.replace(\"
\",\"\").replace(\"
\",\"\").replace(\"\",\"\").replace(\"
相关标签:
2条回答
  • 2021-01-11 12:32

    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.

    0 讨论(0)
  • You can use a regular expression to match all of these at the same time:

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

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

    0 讨论(0)
提交回复
热议问题