Reputation: 1116
Is there a way to use a regex with replace
on every occurrence except the last?
For example, I want "abc"
to become "a|b|c"
.
I can do:
"abc".replace(/./g, "$&|");
But that results in a|b|c|
. Is there a way to replace every occurrence except the last? Or to do n occurrences, rather than do all globally with g
? Or am I thinking about this the wrong way?
Upvotes: 0
Views: 92
Reputation: 786291
You can do it without regex:
var s = "abc";
var r = s.split('').join('|');
//=>"a|b|c"
Upvotes: 2
Reputation: 76656
Use a negative lookahead:
"abc".replace(/.(?!$)/g, "$&|"); // => "a|b|c"
Or even:
"abc".split("").join("|"); // => "a|b|c"
Upvotes: 5