Pradeepb
Pradeepb

Reputation: 2562

Replacing value with Regex

I have two variables:

var v1 = 'http://localhost/wa/pradeep'
var v2 = 'http://localhost/wa/pradeep/some/text'

var re = /(\/wa\/\w*\/?)/

var replaceValue = '$&/~tag/test'

console.log(v1.replace(re, replaceValue))

console.log(v2.replace(re, replaceValue))

I want to avoid two consecutive slashes from the second output. Can anyone guide me how can I achieve the same?

may be there is a way to conditionally check if second group is present and then add slash? I could not find a way to achieve it.

Edit: For the second case, there should a slash at the end (after 'test') For ex: http://localhost/wa/pradeep/~tag/test/some/text

Upvotes: 1

Views: 33

Answers (1)

anubhava
anubhava

Reputation: 785146

You need to keep last / outside group and use back-reference of group #1:

var v1 = 'http://localhost/wa/pradeep'
var v2 = 'http://localhost/wa/pradeep/some/text'

var re = /(\/wa\/\w*)(\/?)/

var replaceValue = '$1/~tag/test$2'

console.log(v1.replace(re, replaceValue))

console.log(v2.replace(re, replaceValue))

Upvotes: 1

Related Questions