Skip to content

Instantly share code, notes, and snippets.

@mtourne
Last active August 29, 2015 14:05
Show Gist options
  • Save mtourne/1a343eb4c1f0cc390343 to your computer and use it in GitHub Desktop.
Save mtourne/1a343eb4c1f0cc390343 to your computer and use it in GitHub Desktop.
js cut words
function is_word_char(c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
function cut_words(content) {
var in_word = false;
var start_word = 0;
var word;
var result = [];
var i;
for (i = 0; i < content.length; i++) {
if (is_word_char(content[i])) {
// char is part of a word
if (!in_word) {
// not in a word yet
in_word = true;
start_word = i;
}
} else {
// char is not a word
if (in_word) {
// end of a word
in_word = false;
// now actually cut the word
// if it's more than one character
if (i - start_word > 1) {
word = content.substring(start_word, i).toLowerCase();
result.push(word);
}
}
}
}
if (in_word) {
// we were in a word at the end of the parsing
if (i - start_word > 1) {
word = content.substring(start_word, i).toLowerCase();
result.push(word);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment