user1199434
user1199434

Reputation: 723

Replace dynamic string value using javascript

Here's the question: How can I replace a value in a string that can vary? I'm guessing you need to use a regex..

Here's what i'm trying to do:

  var height = 500;

  var urlstr = "...?height=300&width=200";

  var newurl = urlstr.replace("height=%&","height="+height+"&");

  alert(newurl);

Notice that I'm currently trying to account for the dynamic value using a "%" sign, however this doesn't work.. I'm not great at using regex and would be grateful if any of you could give me a hint, or alternately tell me if I'm approaching this wrongly ;)

Upvotes: 2

Views: 1943

Answers (2)

user1419950
user1419950

Reputation: 326

"%" will be urlencoded "%25".
for your ref,
javascript encodeURIComponent

Upvotes: 2

Blender
Blender

Reputation: 298532

Yep, you'll need regex. Fortunately it isn't very complicated:

var height = 500;
var urlstr = "...?height=300&width=200";
var newurl = urlstr.replace(/(height=)([0-9]+)/, '$1' + height);

alert(newurl);

Upvotes: 3

Related Questions