wong2
wong2

Reputation: 35730

JavaScript regex replacement

I have this string:

var s = '<span style="font-size:13px">20<div class="lblTitle"></div><span>';    

I'd like to replace the 20 to 40, I tried:

a.replace(/>(\d*)</, 40)  

But it will result in:

<span style="font-size:13px"40div class="lblTitle"></div></span>  

the > and < are replaced too...
What should I do?

Upvotes: 0

Views: 99

Answers (2)

Abdul Munim
Abdul Munim

Reputation: 19217

You can't replace a particular group, rather you can use the group value to your replacement value. You can just use string replacement, regex is not quite required here. It would, if you have used the value 20 somewhere in your replacement.

Using regex in this case is a over kill and as well as hamper your performance just to replace a simple text. Better to use string.replace without regex param.

a.replace(">20<", 40);

Please mind that, you haven't mentioned that you want to replace all numbers in >/d+< format, and if that is your requirement then just go with regex like this:

a.replace(/>(\d*)</, ">40<")

Upvotes: 0

Teneff
Teneff

Reputation: 32158

You could match the > and < and then put them next to the replacement:

.replace(/(>)\d*(<)/, "$140$2")

or simply use:

.replace(/>(\d*)</, ">40<")

You are replacing this in string, so you don't need the replacement to be an integer.

Upvotes: 4

Related Questions