Gaurav Soni
Gaurav Soni

Reputation: 411

Regex to separate an ID after a specific word

Can someone please help in splitting an ID after a specific word in a URL. I need to delete a specific ID from URL and insert a custom ID. The url goes like : "/abc/mode/1234aqwer/mode1?query". I need to replace 1234qwer by 3456asdf.

Example:

Input:

/abc/mode/1234aqwer/mode1?query

Output:

/abc/mode/3456asdf/mode1?query

Upvotes: 1

Views: 165

Answers (2)

Niladri Basu
Niladri Basu

Reputation: 10624

This is the solution without using regex. Use ES6's replace instead:

url = "/abc/mode/1234aqwer/mode1?query"

replace = "1234aqwer"
replaceWith = "3456asdf"

console.log(url.replace(replace, replaceWith))

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370979

One option is to .replace /mode/ followed by non-slash characters, with /mode/ and your desired replacement string:

const input = '/abc/mode/1234aqwer/mode1?query';
console.log(
  input.replace(/\/mode\/[^\/]+/, '/mode/3456asdf')
);

Upvotes: 1

Related Questions