user1935987 user1935987 - 5 months ago 8
Javascript Question

Replace all <br> with space in javascript

Having trouble with very simple thing,
How to properly replace all

< br>
and
<br>
in the string with the empty space?

that's what i trying to use:

var finalStr = replaceAll(replaceAll(scope.ItemsList[i].itemDescr.substring(0, 27), "<", " "), "br>", " ");
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}


receiving the same string.

Answer

you can achieve that using this:

str = str.replace(/<br\s*\/?>/gi,'&nbsp;');

This will match:

  • <br matches the characters <br literally (case insensitive)
  • \s* match any white space character [\r\n\t\f ]
    • Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
  • \/? matches the character / literally
    • Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy] > matches the characters > literally
  • g modifier: global. All matches (don't return on first match)
  • i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

You can see a example for matching here

Comments