在 JavaScript 字符串中获取单词 #n

发布于 2024-10-23 00:07:41 字数 107 浏览 1 评论 0原文

我如何使用 javascript 在字符串中获取单词 # n 。即,如果我想得到“南瓜派和冰淇淋”中的第 3 个单词,我希望返回“and”。有没有一些小功能可以做到这一点,或者有人可以写一个吗?谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

淡水深流 2024-10-30 00:07:42

使用 split 函数将各个单词放入列表中,然后只获取索引 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.

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.
最单纯的乌龟 2024-10-30 00:07:42

一个非常简单的解决方案是:

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

但是,这没有考虑其他空格(制表符、换行符...)或句点和逗号。

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.

冰之心 2024-10-30 00:07:42

或者使用非基于单词的分割:“test,test2 test3”.split(/\W/) 将产生:[test,test2,test3]。

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

陌伤浅笑 2024-10-30 00:07:41

使用 string.split() 方法在“”字符上分割字符串,然后返回数组的第 n-1 个元素(此示例不包括任何边界检查,因此要小心):

var getNthWord = function(string, n){
    var words = string.split(" ");
    return words[n-1];
}

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 2024-10-30 00:07:41

我认为你可以根据空间分割字符串,获取数组,然后从索引 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 ];

当然,错误处理留给你了。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文