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?

3
  • It would be better to create an object literal of your params, then simply replace the value and redirect with new params. Commented Apr 7, 2017 at 15:13
  • Here and here. Commented Apr 7, 2017 at 15:14
  • 2
    Possible duplicate of How can I replace a regex substring match in Javascript? Commented Apr 7, 2017 at 15:15

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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?

Comments

1

It should be as easy as

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

str = str.replace(/(radius=)(\d+)/, "$1" + n);

1 Comment

Why to use capturing groups and backreference if it could be avoided? Especially second capturing group seem unnecessary.
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

3 Comments

window.location.search.substr(1) would be better imho as a comment.
@TimVermaelen possible, has to been benchmarked what is faster
I don't think it's faster really, just more expressive on the part you want to match. If the '?' is not an issue, the substr(1) can be omitted.
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.

Comments

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

'

3 Comments

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.
Thanks i fixes the str and replacement, i actually was tinkering in my editor and pasted the wrong script.
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.

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.