BobbyJones
BobbyJones

Reputation: 1364

Modifying an existing RegEx to accommodate also replacing <nbsp;>'s with a blank space

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

Upvotes: 0

Views: 75

Answers (2)

Jason Cust
Jason Cust

Reputation: 10909

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.

Upvotes: 1

Haseeb Jehanzeb
Haseeb Jehanzeb

Reputation: 319

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

Upvotes: 0

Related Questions