Reputation: 83
I've been coding a simple chat bot, and everything is done except for the sentence decomposition.
How would I create a function to decompose a sentence that does the following?
I'm still learning JavaScript, and would like to know how to best do this.
Upvotes: 2
Views: 279
Reputation: 785058
Consider this code:
s = 'Filter out commas, exclamation points, and periods.';
arr = s.toLowerCase().replace(/[,!.]/g, ' ').split(/ +/).filter(Boolean);
//=> ["filter", "out", "commas", "exclamation", "points", "and", "periods"]
Upvotes: 1
Reputation: 149010
A simple solution would be something like this:
var result = input.toLowerCase().match(/[\w'-]+/g);
The toLowerCase
converts the string to lowercase, then match
will find any sequence of one or more word characters (which includes letters, numbers, and underscores), apostrophes, or hyphens.
For example:
var input = "I'm still learning JavaScript, and would like to know how to best do this.";
var result = input.toLowerCase().match(/[\w'-]+/g);
console.log(result); // ["i'm", "still", "learning", "javascript", "and", "would", "like", "to", "know", "how", "to", "best", "do", "this"]
Upvotes: 4