Reputation: 63
Suppose I have string:
var a = '/c/Slug-A/Slug-B/Slug-C'
I have 3 possibility:
var b = 'Slug-A' || 'Slug-B' || 'Slug-C'
My expectation:
if (b === 'Slug-A') return 'Slug B - Slug C';
if (b === 'Slug-B') return 'Slug A - Slug C';
if (b === 'Slug-C') return 'Slug A - Slug B';
What I've done so far:
a.replace(b,'')
.replace(/\/c\//,'') // clear /c/
.replace(/-/g,' ')
.replace(/\//g,' - ')
Then, I'm stuck
Any help would be appreciated. Thanks
Upvotes: 1
Views: 87
Reputation: 32327
Do it this way
var a = '/c/Slug-A/Slug-B/Slug-C'
var b = 'Slug-A'
//var b = 'Slug-B'
//var b = 'Slug-C'
var k = a.replace(b,'')
.replace(/\/c\//,'') // clear /c/
.replace(/-/g,' ')
.match(/[a-zA-Z -]+/g).join(" - ")
console.log(k)
working array here
Upvotes: 0
Reputation: 18987
Try this, I made it as simple as possible.
var a = '/c/Slug-A/Slug-B/Slug-C';
var b = 'Slug-A';
var regex = new RegExp(b+'|\/c\/|-|\/','g');
alert(a.replace(regex, " ").trim().replace(/(\s.*?)\s+/,'$1 - '));
//OR
alert(a.replace(regex, " ").trim().match(/\w+\s\w/g).join(' - '));
Explanation
1) b+'|\/c\/|-|\/','g'
= matches b
value, /c/
, -
and /
2) a.replace(regex, " ")
= replace all the matched part by space. so a would beSlug A Slug B
3) .replace(/(\s.*?)\s+/,'$1 - ')
= match two spaces with anything within the spaces. And then replace it with the match + ' - '
appended to it.
Note that we have grouped the part (\s.*?)
in the regex (\s.*?)\s+
. So this grouping is done so that It can be used while replacing it with a new text. $1
holds the grouped part of the matched text so $1 = " A"
. So what I am doing is I match the regex Eg : " A "
and replace only the grouped part ie " A"
with " A"
+ " - "
= " A - "
.
4) .match(/\w+\s\w/g).join(' - ')
= match all the part where characters followed by a space followed by a character. match
will return a array of matched parts. So then I join this array by using join
.
Upvotes: 1
Reputation: 2010
Try this:
var a = '/c/Slug-A/Slug-B/Slug-C'
var b = 'Slug-A' || 'Slug-B' || 'Slug-C'
var reg = new RegExp(b.replace(/([A-z]$)/,function(val){return '[^'+val+']'}),'g');
a.match(reg).map(function(val){return val.replace('-',' ')}).join(' - ');
Explication:
the replacement of the string b
catch the last latter of the string and replace it with the ^
regex sign. this mean that instead of capture it it will ignore it.
That mean that mean that now it will match only the Slag-
that isn't contain the last char.
All there is to do is to return it with any join you like.
Upvotes: 1