Skip to content

Instantly share code, notes, and snippets.

@IgorMing
Last active May 6, 2018 19:24
Show Gist options
  • Save IgorMing/5e658b9d1e910134cf2dd105b0bca39d to your computer and use it in GitHub Desktop.
Save IgorMing/5e658b9d1e910134cf2dd105b0bca39d to your computer and use it in GitHub Desktop.
A function which can help you to do something in a phrase in either specific words or specific parts from the phrase.
function wordWrapper(text, wrapperFunc, ...wordsToWrap) {
// Separate the phrase with all the words and characters "!.,:?"
const splittedText = text.match(/([\A-zÀ-ÿ]+|([!.,:?]))/gi);
// Convert everything for lower case, to compare it correctly
const lowerWords = wordsToWrap.map(each => each.toLowerCase());
// Wrap every word doing what the function suggests to do
const wrappedSplittedText = splittedText.reduce((acc, curr) => {
acc.push(lowerWords.includes(curr.toLowerCase()) ? wrapperFunc(curr) : curr);
return acc;
}, []);
// Join the words again, putting space only when is joining strings, unconsidering special characters
return wrappedSplittedText.reduce((acc, curr) => {
const additionalChar = curr.match(/[\A-zÀ-ÿ]+/) === null ? '' : ' ';
return `${acc}${additionalChar}${curr}`;
}, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment