开发者

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!


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];
}


I think you can split your string based on space, get the array and then look for value from the index n-1.

var myStr = "Pumpkin pie and ice cream";
var strArr = myStr.split(String.fromCharCode(32)) //ascii code for space is 32.

var requiredWord = strArr[n-1];
var firstWord = strArr[0];
var lastWord = strArr[ strArr.length - 1 ];

Ofcourse error handling is left to you.


Use the split function to get the individual words into a list, then just grab the word that's in index n - 1.

var sentence = "Pumpkin pie and ice cream";
var words[] = sentence.split(" ");
print words[2]; // if you want word 3, since indexes go from 0 to n-1, rather than 1 to n.


A very simple solution would be:

var str = "Pumpkin pie and ice cream"; //your string
var word = 3; //word number
var word = str.split(" ")[word - 1];

However, this does not take consideration of other whitespace(tabs, newlines...) or periods and commas.


Or use the non-word based split: "test,test2 test3".split(/\W/) would yield: [test,test2,test3].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜