0

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?

asked Nov 29, 2011 at 8:10

2 Answers 2

4

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.

answered Nov 29, 2011 at 8:17
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for recognizing that it doesn't need to maintain the brackets, as they'll be easily replaced.
0

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<")
answered Nov 29, 2011 at 8:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.