Skip to content

Instantly share code, notes, and snippets.

@petergi
Last active December 27, 2023 22:31
Show Gist options
  • Select an option

  • Save petergi/3acdede7f0a175d6ee572979dd8a559a to your computer and use it in GitHub Desktop.

Select an option

Save petergi/3acdede7f0a175d6ee572979dd8a559a to your computer and use it in GitHub Desktop.
Converts a given string into an array of words
// Replaced the split method with the match method, which uses a regular expression to split the string into an array of words.
// Also removed the filter(Boolean) call since the match method already returns an array with only the matched words.
/**
* Returns an array of all words in a given string that match a given pattern.
*
* @param {string} str - The input string to search for words.
* @param {RegExp} pattern - The pattern to match words against. Defaults to /[a-zA-Z-]+/g.
* @return {Array} - An array of words that match the given pattern.
*/
function words(str, pattern = /[a-zA-Z-]+/g) {
return str.match(pattern) || []
}
words("I love javaScript!!") //=
words("python, javaScript & coffee") //=
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment