14
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.

Matt Burland
  • 43,406
  • 17
  • 95
  • 164
Hoser
  • 4,814
  • 9
  • 43
  • 64
  • 3
    replace one instance versus replace all. see http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript – David Fleeman Oct 24 '13 at 20:09
  • 1
    or you could remove all HTML tags (which I think is what you want) => http://stackoverflow.com/questions/1499889/remove-html-tags-in-javascript-with-regex – PlantTheIdea Oct 24 '13 at 20:09
  • 1
    A basic example works here: http://jsfiddle.net/MQNGJ/ – j08691 Oct 24 '13 at 20:14

2 Answers2

21

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.

Karl-Johan Sjögren
  • 15,390
  • 7
  • 60
  • 66
3

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.

r3mainer
  • 22,965
  • 3
  • 45
  • 81