I have a string of text like https://test.com/id/3/5000/333 and I would like to replace the last number 5000 and 3000 with any arbitrary number.
How to do it using regular expression in javascript?
Thanks
2 Answers
What if you had queryParams? You can try to construct a URL object from the original URL string and manipulate the 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);
3000in your url. Please show expected output for 3 or more URLs.