Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  14] [ 5]  / answers: 1 / hits: 27173  / 7 Years ago, mon, may 15, 2017, 12:00:00

I'm having the below string in my node js.



var textToReplace = Your <b class =b_1>1</b> payment due is $4000.Your 
<b class =b_1>2</b> payment due is $3500. Your <b class =b_1>3</b>
payment due is $5000.;


Here I want to replace <b class =b_1>*</b> with ''. The output is Your 1 payment due is $4000.Your 2 payment due is $3500. Your 3 payment due is $5000..



If this is a normal replace I wouldn't have had any problem, but here I think the best way to replace is by using Regex. This is where I'm confused. In java we have a stringVariableName.replaceAll() method. please let me know how can I do this.



Thanks


More From » node.js

 Answers
30
var newString = textToReplace.replace(/<b.*?>(.*?)</b>/g, '$1');





Explanation:



<b.*?> : matches the <b ...> opening tag (using the non-greedy quantifier to match as few as possible)
(.*?) : matches the content of the <b></b> tag (should be grouped so it will be used as a replacement text), it uses the non-greedy quantifier too.
</b> : matches the closing tag
g : global modifier to match as many as possible


then we replace the whole match with the first captured group $1 which represents the content of the <b></b> tag.






Example:





var str = Your <b class =b_1>1</b> payment due is $4000.Your <b class =b_1>2</b> payment due is $3500. Your <b class =b_1>3</b> payment due is $5000.;

var newString = str.replace(/<b.*?>(.*?)</b>/g, $1);

console.log(newString);








Regex101 example.


[#57782] Friday, May 12, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isham

Total Points: 69
Total Questions: 86
Total Answers: 86

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;