Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string regex replace in node js

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

like image 607
user3872094 Avatar asked May 15 '17 15:05

user3872094


People also ask

How do you replace a section of a string in regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.

Can regex replace characters?

They use a regular expression pattern to define all or part of the text that is to replace matched text in the input string. The replacement pattern can consist of one or more substitutions along with literal characters. Replacement patterns are provided to overloads of the Regex.

How do you replace a character in a string in node JS?

Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.


1 Answers

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.

like image 108
ibrahim mahrir Avatar answered Oct 06 '22 08:10

ibrahim mahrir