From 4280957a102c0196041234786c2cd97189bd4761 Mon Sep 17 00:00:00 2001 From: Arjun Mahishi Date: Wed, 20 Dec 2017 12:26:10 +0530 Subject: [PATCH] Updated function with regex --- snippets/stringToArrayOfWords.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/snippets/stringToArrayOfWords.md b/snippets/stringToArrayOfWords.md index 2749a6869..f0c5f149b 100644 --- a/snippets/stringToArrayOfWords.md +++ b/snippets/stringToArrayOfWords.md @@ -2,13 +2,10 @@ Converts a given string into an array of words -First create an array of dirt that you want to remove from the string. Then replace each dirt with an empty string. Use `String.split(/[\W_]+/)` to convert the string to an array with the use of regex. +Use `String.split(/[\W_]+/)` to convert the string to an array with the use of regex. ```js -const stringToArrayOfWords = str => { - [".", ",", "?", "!", "& ", "(", ")", "[", "]"].map(d => str = str.split(d).join("")); - return str.split(/[\W_]+/); -} +const stringToArrayOfWords = (str, pattern = /[\W_]+/) => str.split(pattern).filter(Boolean) // stringToArrayOfWords("I love javaScript!!") -> ["I", "love", "javaScript"] // stringToArrayOfWords("python, javaScript & coffee") -> ["python", "javaScript", "coffee"]