Skip to content

Instantly share code, notes, and snippets.

@peterwiebe
Last active September 3, 2021 19:37
Show Gist options
  • Save peterwiebe/97cbb0c2b356e5fa5a04550a5d65872a to your computer and use it in GitHub Desktop.
Save peterwiebe/97cbb0c2b356e5fa5a04550a5d65872a to your computer and use it in GitHub Desktop.
JavaScript utility to split a string into array that includes the delimiter and can ignore case
/*
* Example splitWithDelimiter({query: 'the', suggestion: 'The quick brown fox jumps over the lazy dog.', shouldIgnoreCase: true})
* Evaluates to ['The', ' quick brown fox jumps over ', 'the', ' lazy dog.'];
*/
function splitWithDelimiter ({delimiter, target, shouldIgnoreCase}) {
const result = [];
const formattedTarget = shouldIgnoreCase ? target.toLowerCase() : target;
const formattedDelimiter = shouldIgnoreCase ? delimiter.toLowerCase() : delimiter;
const doesStartWithDelimiter = formattedTarget.startsWith(formattedDelimiter);
const doesEndWithDelimiter = formattedTarget.endsWith(formattedDelimiter);
const mismatchedFragments = formattedTarget.split(formattedDelimiter);
let resultLength = 0;
if (doesStartWithDelimiter) {
result.push(target.substring(0, delimiter.length));
resultLength = delimiter.length;
}
mismatchedFragments.forEach((fragment, index) => {
if (!fragment) return;
result.push(target.substring(resultLength, resultLength + fragment.length));
resultLength += fragment.length;
if (index < mismatchedFragments.length && resultLength < target.length) {
const characters = target.substring(resultLength, resultLength + delimiter.length);
result.push(characters);
resultLength += delimiter.length;
}
})
if (doesEndWithDelimiter) {
result.push(target.substring(target.length - delimiter.length, target.length));
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment