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?
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?
- It would be better to create an object literal of your params, then simply replace the value and redirect with new params. – Tim Vermaelen Commented Apr 7, 2017 at 15:13
- Here and here. – revo Commented Apr 7, 2017 at 15:14
- 2 Possible duplicate of How can I replace a regex substring match in Javascript? – revo Commented Apr 7, 2017 at 15:15
6 Answers
Reset to default 4You 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);
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?
It should be as easy as
var str='/results?radius=4000&newFilter=true';
var n = 1234;
str = str.replace(/(radius=)(\d+)/, "$1" + n);
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
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.
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
'