2

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 ;)

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks that worked perfectly, if you don't mind me asking, what does this bit do '$1' ? I'm a little bit confused by that part.. PS blender rules :)
$1 refers to the first matched group, which is height=. I was lazy and didn't want to write out height= so I matched it with $1 instead. $2 holds the contents of the old height, just in case you'll ever need it.
And yes, Blender rules ;) It's awesome.
2

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

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.