1

I'm trying to use .replace() to replace a specific part of a URL but I'm not sure how to go about it.

Specifically, I'm taking a string that looks like this:

'param1=www.DOMAIN.NAME&param2=NUM1&param3=true&param4=25'

I'd like to change param2 at my own discretion using jquery.

Currently I just use .replace('NUM1', newParam); but as you can see once 'NUM1' changes to the new parameter that the varaible newParam gives it, I can't then change it again as it will no long find 'NUM1'.

Robbie Wxyz
  • 7,671
  • 2
  • 32
  • 47
  • In that case you can code `replace(newParam, anotherNewParam)`, but it's very fragile, you should target the `param2` and change it's value. http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript?rq=1 – Ram Mar 07 '14 at 21:45
  • Rip the values out of the string and create a new string. `$.param({param1: param1, param2: "myNewValue", param3: param3, param4:param4});` – Kevin B Mar 07 '14 at 21:50
  • How about this regex `.replace('(param2=)[^&]+','$1'+newParam);`? – Robbie Wxyz Mar 07 '14 at 22:05

2 Answers2

2

If you know all the other aspects of the string, you could do a quick hack and concatenate the string:

str = 'param1=www.DOMAIN.NAME&param2=' + NUM1 + '&param3=true&param4=25'

Not elegant, but it'd work.

Alternatively if that string is variable but the NUM1 is always there, you could split('NUM1'), then join(newParam)

e.g.,

str = 'param1=www.DOMAIN.NAME&param2=NUM1&param3=true&param4=25'
str.split('NUM1').join(newParam);
Russell Ingram
  • 114
  • 1
  • 1
  • 11
0

If I were you I would look into a jQuery plugin for handling query strings. Surely this will always be a querystring-like string. A little searching turned up this, but these kinds of plugins have been around a long time and you're likely to find one that precisely suits your needs.

Randy L
  • 14,384
  • 14
  • 44
  • 73