Having the following string:
var str = "JavaScript is used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more. JavaScript is easy to learn. You will enjoy it.";
How can I divide it by removing blank spaces, commas and periods, in such a way that it gives me the result:
["JavaScript", "is", "used", "in", "billions", "of", "Web", "pages", "to", "add", "functionality", "validate", "forms", "communicate", "with", "the", "server", "and", "much", "more", "JavaScript", "is", "easy", "to", "learn", "You", "will", "enjoy", "it"]
1) We remove all the characters we don't need (dot, commas) with the regular expression
cadena.replace(/[\. ,]+/g, " ");
2) Through the spaces we can divide with the function
split(" ")
obtaining an arrayOne option would be to use a regular expression as a parameter to the method
split(regex)
, passing it a group of characters [] with which it will match for this occasion (space , period , comma)/[ .,]/
this expression will cause blanks in the array according to its string so you could use the special character + to take into account 1 or more matches
But this will still generate an additional empty element in the array, you could apply
filter
to remove it, of course this is an additional step, you could do it in multiple ways.This could also work, if you want to split the string into words , regardless of any symbols.