2

I have this string

/results?radius=4000&newFilter=true

and I need to replace radius=4000 with radius=n where n is a variable.

How can I use String.replace() method with regex to match that part?

nick
  • 2,819
  • 5
  • 33
  • 69
  • It would be better to create an object literal of your params, then simply replace the value and redirect with new params. – Tim Vermaelen Apr 07 '17 at 15:13
  • [Here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) and [here](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions). – revo Apr 07 '17 at 15:14
  • 2
    Possible duplicate of [How can I replace a regex substring match in Javascript?](http://stackoverflow.com/questions/3598042/how-can-i-replace-a-regex-substring-match-in-javascript) – revo Apr 07 '17 at 15:15

6 Answers6

4

You can use /radius=\d+/ to match "radius=" followed by any number of digits. With this we can use the replace() method to replace it with the desired value:

var str = "/results?radius=4000&newFilter=true";
var replacement = 123;

var newStr = str.replace(/radius=\d+/, "radius=" + replacement);

console.log(newStr);
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • Both `match` parameter in anonymous function, as well as that anonymous function itself are unnecessary. Why not just `str.replace(/radius=\d+/, "radius=" + replacement)`? Also, `newStr` has missing semicolon at the end. – Przemek Apr 07 '17 at 15:53
2

If you want to get all parameters you can try this :

function getParams(uri) {

 var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;
        
    while (tokens = re.exec(uri)) {
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }
    return params;
}

var str='/results?radius=4000&newFilter=true';

str = str.substring(str.indexOf("?"));
params = getParams(str);

console.log(params);
console.log('radius => ', params['radius']);

This answer is from this post: How to get the value from the GET parameters?

Community
  • 1
  • 1
Ankirama
  • 498
  • 4
  • 14
1

It should be as easy as

var str='/results?radius=4000&newFilter=true';
var n = 1234;

str = str.replace(/(radius=)(\d+)/, "$1" + n);
devnull69
  • 16,402
  • 8
  • 50
  • 61
  • Why to use capturing groups and backreference if it could be avoided? Especially second capturing group seem unnecessary. – Przemek Apr 07 '17 at 15:57
1
var url = "/results?radius=4000&newFilter=true"; 
// or window.location.href for current url
var captured = /radius=([^&]+)/.exec(url)[1]; // your 4000
var newValue = 5000;
url = url.replace(captured, newValue);

by this way you can use it to get all your requested parameters too and it is not decimal binded

TypedSource
  • 708
  • 4
  • 12
1

ES6 with regex using positive lookbehind

const string       = '/results?radius=4000&newFilter=true',
      n            = '1234',
      changeRadius = (radius) => string.replace(/(?<=radius=)\d+/, n);

console.log(changeRadius(n));
/* Output console formatting */
.as-console-wrapper { top: 0; }
  • changeRadius is function that takes one parameter (radius) and performs replacement.
  • About the regex: \d+ gets as many digits as possible, (?<=STRING) is a positive lookbehind.

Other regex

Body of changeRadius() function can be replaced with string.replace(/radius=\d+/, 'radius=' + n). It probably has better performance, but original regex is more direct translation of the problem.

Przemek
  • 3,855
  • 2
  • 25
  • 33
0

You can use capturing without remembering the match to capture only the numerical value after 'radius='.

var url = "/results?radius=4000&newFilter=true";

var radius = 123;

var newUrl = url.replace(/(?:radius=){1}(\d+)/, radius);

console.log(newUrl); // logs '/results?radius=4000&newFilter=true'0

'

zak.http
  • 316
  • 4
  • 4
  • First thing, `str` and `replacement` are undefined. Change `url` to `str` and `radius` to `replacement`. Second thing, you miss `=` after `radius`. Third thing, you forgot `'radius=' + ` before `replacement` at position of the second parameter of `replace()` function. Forth thing, why the needless `{1}` and capturing group around `\d+`? And the last thing, I don't know if you would agree, but to me positive lookbehind seem to be better fit rather than non-capturing group. – Przemek Apr 07 '17 at 17:59
  • Thanks i fixes the str and replacement, i actually was tinkering in my editor and pasted the wrong script. – zak.http Apr 07 '17 at 18:22
  • This still gives `"/results?123&newFilter=true"` instead of `/results?radius=123&newFilter=true`. Once again, you forgot `'radius=' +` before `radius` at position of the second parameter of `replace()` function. – Przemek Apr 08 '17 at 15:13