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?
 
    
    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); 
    
    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
 
    
    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.\d+ gets as many digits as possible, (?<=STRING) is a positive lookbehind.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
'
