Last active
December 27, 2023 22:31
-
-
Save petergi/3acdede7f0a175d6ee572979dd8a559a to your computer and use it in GitHub Desktop.
Converts a given string into an array of words
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
| // 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