Skip to content

Instantly share code, notes, and snippets.

@wader
Created September 20, 2016 20:20
Show Gist options
  • Save wader/5c24566287a6ba44024210344e66a2d9 to your computer and use it in GitHub Desktop.
Save wader/5c24566287a6ba44024210344e66a2d9 to your computer and use it in GitHub Desktop.
// regexp split but keep match in array
function regexSplitKeep(re, s) {
re.lastIndex = 0;
let prevLastIndex = 0;
let parts = [];
for (let m = null; (m = re.exec(s)); ) {
if (prevLastIndex !== -1 && m.index !== prevLastIndex) {
parts.push(s.substr(prevLastIndex, m.index - prevLastIndex));
}
parts.push(s.substr(m.index, re.lastIndex-m.index));
prevLastIndex = re.lastIndex;
}
if (prevLastIndex < s.length) {
parts.push(s.substr(prevLastIndex));
}
return parts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment