Hoser
Hoser

Reputation: 5044

Javascript .replace() not working

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.

Upvotes: 15

Views: 39773

Answers (3)

Manoj V
Manoj V

Reputation: 1

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,"+"));

Upvotes: 0

r3mainer
r3mainer

Reputation: 24547

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.

Upvotes: 3

Karl-Johan Sj&#246;gren
Karl-Johan Sj&#246;gren

Reputation: 17522

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.

Upvotes: 22

Related Questions