Created
September 20, 2016 20:20
-
-
Save wader/5c24566287a6ba44024210344e66a2d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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