0

If i have a string as follows:

http:/mydomain.com/index.php/this/is/an/amazing/url/param/560/

and i want to replace the value of 560, what is the way to do this.

Would a regex or string function be best used here and if so what would that be since the value can be different.

i.e.

the value can be anything:

http:/mydomain.com/index.php/this/is/an/amazing/url/param/120/
http:/mydomain.com/index.php/this/is/an/amazing/url/param/200/

also the trailing slash may be missing i.e.

http:/mydomain.com/index.php/this/is/an/amazing/url/param/560
4
  • 1
    Yes, use .replace() with regex Commented Jun 25, 2013 at 20:07
  • When you say "the value can be anything", do you mean you want to replace any number at the end of the URL, or the value is a dynamic input to the program? Commented Jun 25, 2013 at 20:10
  • And if the original URL ends with /, does that have to be retained in the result? Commented Jun 25, 2013 at 20:12
  • Hi, yes to both of those Commented Jun 25, 2013 at 20:19

3 Answers 3

3

You could do something like this:

var new_number = 5;

url = url.replace(/\d+(\/)?$/, new_number + "$1");

This looks for numbers, then optionally one slash, then the end of the string. So you won't match things like http://example.com/some/other/1234/numbers.

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

2 Comments

Welcome to stackoverflow.com. This is a good answer even though (\/) looks like a vulgar ascii art.
Ha, I suppose it does! I think that just adds to its charm.
1

Regex is probably the easiest solution in this case:

url.replace(/\/\d+\/?$/, '/' + newNumber);

This Regex specifically looks for anything ending in a slash, 1 or more digits, then an optional slash.

1 Comment

this will result in param123; don't forget to replace the / before the number.
0
var regex = new RegExp('\b'+value+'\b');
newurl = url.replace($regExp, newvalue);

Comments

Your Answer

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.