Reputation: 1364
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
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 something else';
var txt = str.replace(/(<br\s*\/?>| )/mg, function (match) {
return match === ' ' ? ' ' : '\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 something else';
var txt = str.replace(/<br\s*\/?>/gm, '\n').replace(/ /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
Reputation: 319
You may use something like this
var txt = str.replace(/<br ?/?>/g, '\n').replace(/ /g, ' ');
but you can't do 2 replacements using 1 regex
Upvotes: 0