Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get word #n in javascript string

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!

like image 492
Leticia Meyer Avatar asked Apr 24 '26 10:04

Leticia Meyer


1 Answers

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];
}
like image 71
Justin Niessner Avatar answered Apr 27 '26 00:04

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!