Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all <br> tag 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?

This is what I'm trying to use, but I'm receiving the same string.:

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);
}
like image 638
user1935987 Avatar asked Jun 14 '16 14:06

user1935987


People also ask

How do you replace Br?

In the opening Find and Replace dialog box, click on the Find what box and press the Ctrl + Shift + J keys together, enter br into the Replace with box, and then click the Replace All button.

What is $1 in replace Javascript?

In your specific example, the $1 will be the group (^| ) which is "position of the start of string (zero-width), or a single space character". So by replacing the whole expression with that, you're basically removing the variable theClass and potentially a space after it.

How do you replace a line break in a string?

In order to replace all line breaks from strings replace() function can be used.


1 Answers

You can achieve that using this:

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

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])

SNIPPET BELOW

let str = "This<br />sentence<br>output<BR/>will<Br/>have<BR>0 br";
str = str.replace(/<br\s*\/?>/gi, ' ');
console.log(str)
like image 81
dippas Avatar answered Oct 06 '22 16:10

dippas