简体   繁体   中英

Javascript regex match number after string

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

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

'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM