user5109824 February 2016

Replace string in javascript

I have this string:

1<div>2</div><div>3</div><div>4</div>

if i replace the values

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

it will replace only the first div

1-2</div><div>3</div><div>4</div>

how to replace all div?

Answers


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, '-');
document.write(str);

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>', '-');
document.write(str);

Post Status

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

Search




Leave an answer