Tuesday, May 18, 2021

JavaScript splitKeep

Helper function for split keep. Reference: https://medium.com/@shemar.gordon32/how-to-split-and-keep-the-delimiter-s-d433fb697c65
String.prototype.splitKeep = function (tokens) {
    const escaped = escapeRegExp(tokens);
    return this.split(new RegExp(`(?=[${escaped}])|(?<=[${escaped}])`, 'g'));
};


// Not built-in yet https://github.com/tc39/proposal-regex-escaping

// Use a good one for the meantime https://stackoverflow.com/questions/3115150/how-to-escape-regular-expression-special-characters-using-javascript
function escapeRegExp(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
Add this when using TypeScript:
declare global {
    interface String {
        splitKeep(tokens: string): string[];
    }
}

No comments:

Post a Comment