15
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
  • 44,552
  • 18
  • 99
  • 171
Hoser
  • 4,974
  • 9
  • 45
  • 66
  • 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

3 Answers3

22

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
  • 16,544
  • 7
  • 59
  • 68
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
  • 23,981
  • 3
  • 51
  • 88
0

if you want to remove the space completely from a string value. you ca use

/g

var str="javasript is amazing when you crack it";
alert(str.replace(/ /g,"+"));