0

I need your help,

How can the existing code below be modified such that it not only takes into account replacing all the <br>'s with \n's but also all the <nbsp;>'s anywhere in a string with the space separator in javascript?

Here is the existing code that needs to be modified:

var txt = str.replace(/<br\s*\/?>/mg,"\n")
Sam Hosseini
  • 813
  • 2
  • 9
  • 17
BobbyJones
  • 1,331
  • 1
  • 26
  • 44
  • [You can't parse (X)HTML with regex](http://stackoverflow.com/a/1732454/1529630). And do you mean ` `? – Oriol Jun 19 '15 at 17:04

2 Answers2

1

If you want to do it with one regexp, replace accepts a function as the replacer so you could leverage that with a group match:

var str = 'some string <br/> and&nbsp;something else';
var txt = str.replace(/(<br\s*\/?>|&nbsp;)/mg, function (match) {
  return match === '&nbsp;' ? ' ' : '\n';
});

document.write('<pre>' + txt + '</pre>');

If not, you can also chain together as many replace calls as you want:

var str = 'some string <br/> and&nbsp;something else';
var txt = str.replace(/<br\s*\/?>/gm, '\n').replace(/&nbsp;/gm, ' ');
document.write('<pre>' + txt + '</pre>');

The main benefit of using one replace is that it won't need to check the entire string twice. However this does make the code a bit harder to read and possibly to maintain if you need to add/edit which entities you want to replace. So depending on the length of the string to be checked you would need to strike a balance between performance and readability/maintainability.

Jason Cust
  • 10,743
  • 2
  • 33
  • 45
0

You may use something like this

var txt = str.replace(/<br ?/?>/g, '\n').replace(/&nbsp;/g, ' ');

but you can't do 2 replacements using 1 regex

Haseeb Jehanzeb
  • 319
  • 5
  • 9