Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove all <br> from a string

I have a string that i would like to remove all occurrences of <br>

I tried this and it did not work.

    productName = productName.replace("<br>"," ");

However this worked but only for the first <br>

    productName = productName.replace("&lt;br&gt;"," ");

How would I get it to work for all <br> in the string.

Edit: this is the string...

00-6189 Start Mech Switch&lt;br&gt;00-6189 Start Mech Switch&lt;br&gt;00-6189 Start Mech Switch&lt;br&gt;

My apologies for being a little misleading with the <br> as it should have been &lt;br&gt;

like image 619
user357034 Avatar asked Nov 15 '10 12:11

user357034


People also ask

How do I remove all line breaks from a string?

Remove All Line Breaks from a String We can remove all line breaks by using a regex to match all the line breaks by writing: str = str. replace(/(\r\n|\n|\r)/gm, ""); \r\n is the CRLF line break used by Windows.

How to remove rn in JavaScript?

I found this in JavaScript line breaks: someText = someText. replace(/(\r\n|\n|\r)/gm, ""); That should remove all kinds of line breaks.


3 Answers

Using regular expression you can use this pattern

/(<|&lt;)br\s*\/*(>|&gt;)/g
productName = productName.replace(/(<|&lt;)br\s*\/*(>|&gt;)/g,' ');

That pattern matches

 <br>, <br />,<br/>,<br     />,<br  >,
 or &lt;br&gt;, &lt;br/&gt;, &lt;br /&gt;

etc...

like image 199
DavideDM Avatar answered Sep 23 '22 16:09

DavideDM


Looks like your string is encoded so use

productName = productName.replace(/&lt;br&gt;/g," ");

note the g after the regular expression which means globally, to match all occurrences.

demo at http://www.jsfiddle.net/gaby/VDxHx/

like image 41
Gabriele Petrioli Avatar answered Sep 26 '22 16:09

Gabriele Petrioli


You could use the g flag in your regular expression. This indicates that the replace will be performed globally on all occurrences and not only on the first one.

productName = productName.replace(/\<br\>/g," ");

Of course you should be aware that this won't replace <br/> nor <br /> but only <br>.

See an example of this working on ideone.


UPDATE:

Now that you've provided an example with your input here's a working regex you might use to replace:

productName = productName.replace(/&lt;br&gt;/g, ' ');
like image 25
Darin Dimitrov Avatar answered Sep 23 '22 16:09

Darin Dimitrov