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??
CodePudding user response:
You could use a regex replacement:
var url = "url = /api/v1/customers/123/spend/456";
var output = url.replace(/\/\d (\/|$)/g, "/*$1");
console.log(output);
The regex pattern used here matches:
/ / separator
\d a number
(/|$) either / or the end of the URL (capture)
Note that we replace with /*$1
, where $1
may or may not be a captured separator (not in the case of the final number).
CodePudding user response:
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