-1

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
  • Please visit help center, take tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output, preferably in a Stacksnippet Commented Mar 9, 2023 at 17:22
  • You do not have 3000 in your url. Please show expected output for 3 or more URLs. Commented Mar 9, 2023 at 17:33

2 Answers 2

0

You can use \d+/\d+$ to match two consecutive groups of digits separated by a slash before the end of the string.

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.