How would I get word # n in a string with javascript. I.e. if I want to get word #3 in "Pumpkin pie and ice cream", I want "and" returned. Is there some little function to do this, or could someone write one? Thanks!
Use the string.split() method to split the string on the " " character and then return the nth-1 element of the array (this example doesn't include any bounds checking so be careful):
var getNthWord = function(string, n){
var words = string.split(" ");
return words[n-1];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With