简体   繁体   中英

How to replace multiple instances of <br/> tags with something else in string in javascript?

I have a variable:

var test = "Hello<br/><br/>World";

I want to have a function that can replace those with newlines so that the result is:

Hello

World

I tried using:

test = test.replace('<br/>','\r\n');

However this just replaces one occurrence of the
and not all of them. I want to make sure that it replaces all occurrences of
in the text, be it located right next to each other, or if they are in different parts of the same string.

When you use string as a pattern in replace function it replaces only first occurrence. You need to use regex pattern with g flag

 var test = "Hello<br/><br/>World"; test = test.replace(/<br\\/>/g,'\\r\\n'); console.log(test)

There's proposal for replaceAll in which you can use string as pattern and replace all the occurrences

try using this:

var test = "Hello<br/><br/>World";
test = test.replace(/<[^>]*>/g, '\r\n');
console.log(test)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM