Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Created June 16, 2012 04:37
Show Gist options
  • Select an option

  • Save wilmoore/2939940 to your computer and use it in GitHub Desktop.

Select an option

Save wilmoore/2939940 to your computer and use it in GitHub Desktop.
Accept a string, tokenize into words (delimited by spaces), output words with reversed characters, words stay in original order
function wordify(string) {
var index = 0;
var word = '';
var words = [];
var end = string.length - 1;
while(string[index] !== undefined) {
word += /^\s/.test(string[index]) ? '' : string[index];
if (/\s/.test(string[index]) || index === end) {
words.push(word);
word = '';
}
index++;
}
return words;
}
function reverse_words(words) {
return words.map(function(word){
var end = word.length - 1;
var rword = '';
for (i = end; i >= 0; --i) {
rword += word[i];
}
return rword;
});
}
var text = 'Sorry but my dog ate my homework';
console.log(text);
var words = wordify(text);
//console.log(words);
var rwords = reverse_words(words);
//console.log(rwords);
var rtext = rwords.join(' ');
console.log(rtext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment