Give the following string:

http://foobar.com/trusted/123/views/AnalyticsInc

..where 123 will be a number anywhere between 0 and 9999999, I need to be able to dynamically replace said value with a different value

I assume the best way to approach this is to do a string.replace with some sort of regex pattern, since we can count on the fact that "/trusted/" and "/views/" will always surround the value that needs to be swapped out.

var foo='http://foobar.com/trusted/123/views/AnalyticsInc';
var newvalue=654321;
magic(); //magic happens here
console.log(foo); //returns http://foobar.com/trusted/654321/views/...etc

But my regex kung-fu is so weak I cannot defeat a kitten. Can someone give me a hand? Or if there's a better approach, I'd love to learn it. Thanks!

share|improve this question

feedback

1 Answer

up vote 2 down vote accepted

It will replace the first occurrence of number from 0 to 9999999 in foo string:

foo = foo.replace(/\d{1,7}/, newvalue);

DEMO: http://jsfiddle.net/D4teZ/

share|improve this answer
That sir, is perfect. Thanks. – Russell Christopher Jun 3 at 23:53
You are welcome :) – VisioN Jun 3 at 23:53
More generic would be (/\/\d+\//, '/' + newvalue + '/') so the number string to replace can be 1 or more digits between /. – RobG Jun 4 at 2:46
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.