Home Ask Login Register

Developers Planet

Your answer is one click away!

user5109824 February 2016

Replace string in javascript

I have this string:


if i replace the values

var descriptionVal = desc.replace('<div>', '-').replace('</div>', '-');

it will replace only the first div


how to replace all div?


sebastianbrosch February 2016

You have to use regular expressions to replace. You can use the replace function with global flag g. Checkout the following solution:

var descriptionVal = desc.replace(/<div>/g, '-').replace(/<\/div>/g, '-');

Working example:

var str = "1<div>2</div><div>3</div><div>4</div>";
str = str.replace(/<div>/g, '-').replace(/<\/div>/g, '-');

With a simple string replace, like your example, only the first occurance of each replace function will be replaced:

var str = "1<div>2</div><div>3</div><div>4</div>";
str = str.replace('<div>', '-').replace('</div>', '-');

Post Status

Asked in February 2016
Viewed 1,144 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life