Another easy way to do this is to .split()
the string based on whatever delimiter you plan on using, .filter()
for non-empty elements, and then .join()
with the same delimiter:
JavaScript
var str = "Hi I have |str| way |str||str| too |str||str||str| many breaks";
var x = str.split("|str|").filter(function (d){
return d.length;
}).join("|str|");
console.log(x)
// returns "Hi I have |str| way |str| too |str| many breaks |str|";
This allows you to avoid making a specific regular expression for each case—no escaping characters—and instead run variables through .split()
and .join()
.
Not sure whether or not this solution is faster. It seems to be faster in non-Chromium browsers. I would surmise that Chrome is efficiently, because of the v8 engine, compiling a regex before running it a million times, making the regex solution faster.