Skip to content

Instantly share code, notes, and snippets.

@tyv
Last active June 6, 2017 09:45
Show Gist options
  • Save tyv/7ab6152956518a4f0d11c3bbdb219b39 to your computer and use it in GitHub Desktop.
Save tyv/7ab6152956518a4f0d11c3bbdb219b39 to your computer and use it in GitHub Desktop.
'pp'.split('p') // ["", "", ""]
'apple'.split('p') // ["a", "", "le"]
// need 'apple' as ["a", "", "", "le"]
// 'apppple' with split by 'pp' should be ["a", "", "", "le"] as well
@narqo
Copy link

narqo commented Jun 2, 2017

'apppple'.split(/(pp)/).filter(p => p).map(p => p === "pp" ? "" : p)
// ["a", "", "", "le"]

¯_(ツ)_/¯

@iaroslavshvets
Copy link

const splitter = (word, splitPhrase) => {
       let replaceCount = 0;

	const res = word
            .match(new RegExp(`(${splitPhrase})`))
	    .reduce(() => {
		replaceCount++;
		return word.replace(`(${splitPhrase})`, splitPhrase + splitPhrase);
             }, '')
	    .split(new RegExp(`(${splitPhrase})`))
	    .filter(l => l.length)
	    .map(l => l === splitPhrase ? '' : l);

	return res.length === replaceCount ? res.concat('') : res;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment