1

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?

3 Answers 3

2

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, '/'))
})

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

Comments

0

Try this pattern \/_?api\/v\d+

  1. _? is or condition with and without _
  2. And use with d+ it will match numeric in end of the v1&v2

Demo Regex and explanation

var input1 = '/api/v1'
var input2 = '/_api/v1'

console.log(input1.replace(/\/_?api\/v\d+/g, '/'))
console.log(input2.replace(/\/_?api\/v\d+/g, '/'))

Comments

0

You can do it with a simple or-condition |:

Regular expression: /api/v1|/_api/v1

And with javascript:

const output = input.replace(/\/api\/v1|\/_api\/v1/g, '/');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.