我有这根绳子
/results?radius=4000&newFilter=true我需要将radius=4000替换为radius=n,其中n是变量。
如何使用正则表达式的String.replace()方法来匹配该部分?
发布于 2017-04-07 15:49:46
使用正向后查找的正则表达式的ES6
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是接受一个参数(radius)并执行替换的函数。\d+获取尽可能多的数字,(?<=STRING)是一个正向后视。其他要领
changeRadius()函数的体可以用string.replace(/radius=\d+/, 'radius=' + n)代替。它可能有更好的性能,但原来的正则表达式是更直接的翻译问题。
https://stackoverflow.com/questions/43281509
复制相似问题