Eric Alberson
Eric Alberson

Reputation: 1116

JavaScript replace regex every occurence but the last?

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

Answers (2)

anubhava
anubhava

Reputation: 786291

You can do it without regex:

var s = "abc";
var r = s.split('').join('|');
//=>"a|b|c"

Upvotes: 2

Amal
Amal

Reputation: 76656

Use a negative lookahead:

"abc".replace(/.(?!$)/g, "$&|"); // => "a|b|c"

Or even:

"abc".split("").join("|"); // => "a|b|c"

Upvotes: 5

Related Questions