0

I'm trying to use String.replace() with a regular expression to replace a matched expression.

Like so:

var newStr = loc.replace(/Slide(\d*)/,(i+1));

This expression turns

https://xxxxxxx.net/qa/club/Slide1.PNG

into

https://xxxxxxx.net/qa/club/1.PNG

I just want to replace the numbers after "Slide", without removing the word. How can I do this?

2
  • Is it always "Slide" that you want to remove? Commented Jan 13, 2014 at 21:34
  • @JHuangweb I never want to remove "Slide" Commented Jan 13, 2014 at 21:35

1 Answer 1

3

Use a capture group and insert it in your replacement.

loc.replace(/(Slide)\d*/, '$1' + (i+1));

If the word will always be slide, then you can simply use this without capturing anything

loc.replace(/Slide\d*/, 'Slide' + (i+1));

The paratheses around (i + 1) are important to force the mathematical operation before string concatenation.

If Slide is always followed by a number, change the * to a + in the regular expression.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't want Slide at all. I just want the number. The + seems to Match Slide in addition to the number.

Your Answer

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