Input
'/api/v1' or '/_api/v1'
output
'/'
I could do it like this
const output = input.replace('/api/v1', '/').replace('/_api/v1', '/');
But just curious how can we take advantage of regex in replace method, and do it in a single shot?
Simply make the underscore optional using the ? meta-character.
// using the constructor here to avoid all that forward-slash escaping
const rx = new RegExp('/_?api/v1')
const inputs = ['/api/v1', '/_api/v1']
inputs.forEach(input => {
console.info(input, ' becomes ', input.replace(rx, '/'))
})
Try this pattern \/_?api\/v\d+
_? is or condition with and without _d+ it will match numeric in end of the v1&v2var input1 = '/api/v1'
var input2 = '/_api/v1'
console.log(input1.replace(/\/_?api\/v\d+/g, '/'))
console.log(input2.replace(/\/_?api\/v\d+/g, '/'))