Russell Christopher
Russell Christopher

Reputation: 1707

Javascript string replace using regex expression

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!

Upvotes: 1

Views: 97

Answers (1)

VisioN
VisioN

Reputation: 145458

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/

Upvotes: 2

Related Questions