1

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!

1 Answer 1

2

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/

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

1 Comment

More generic would be (/\/\d+\//, '/' + newvalue + '/') so the number string to replace can be 1 or more digits between /.

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.