javascript 如何使用regex [duplicate]替换此字符串中的最后两个数字

wljmcqd8  于 2023-03-11  发布在  Java
关注(0)|答案(2)|浏览(124)

此问题在此处已有答案

How to replace a number in a URL using JavaScript(3个答案)
Regexp: replace all digits on URL after third slash(1个答案)
昨天关门了。
我有一个像https://test.com/id/3/5000/333这样的文本字符串,我想用任意数字替换最后一个数字50003000。如何在javascript中使用正则表达式?谢谢

zbwhf8kr

zbwhf8kr1#

您可以使用\d+/\d+$来匹配两组连续的数字,这两组数字在字符串结尾之前用斜杠分隔。

let s = 'https://test.com/id/3/5000/333';
let res = s.replace(/\d+\/\d+$/, 123 + '/' + 456);
console.log(res);
6tqwzwtp

6tqwzwtp2#

如果您有queryParams,您可以尝试从原始URL字符串构造一个URL对象并操作pathname

const randomInt = (limit) => Math.floor(Math.random() * limit);

const originalUrl = 'https://test.com/id/3/5000/333?test=true';
const urlObj = new URL(originalUrl);
const parts = urlObj.pathname.split('/').filter(path => path.length);

// Modify the last and second-to-last path values
parts[parts.length - 1] = randomInt(1000);
parts[parts.length - 2] = randomInt(10000);

// Re-join the parts of the path
urlObj.pathname = parts.join('/');

const modifiedUrl = urlObj.toString();

console.log(modifiedUrl);

相关问题