Issue
I have a url in the format url = /api/v1/customers/123/spend/456
I needed to replace the numbers between slashes as *
.Same for numbers in the end of url as *
.
so my expected url output url = /api/v1/customers/*/spend/*
How can we achieve this using RegEx??
Solution
You can do this by using lookaround(lookahead & lookbehind), using these you can match only the numbers.
let pattern = /(?<=\/)\d+(?=\/|$)/g
let url = "/api/v1/customers/123/spend/456"
url = url.replace(pattern, '*')
console.log(url)
(?<=\/)\d+(?=\/|$)
(?<=\/) lookbehind which matches the / before a number
\d+ matches one of more digits
(?=\/|$) loohahead which matches either the / after the number or the end of the string
Answered By – anotherGatsby
Answer Checked By – Candace Johnson (BugsFixing Volunteer)