输出包含3个单词的字符串中的前2个单词

Output first 2 words from a string that contains 3 words

本文关键字:单词 2个 字符串 包含 输出 3个      更新时间:2023-09-26

我想显示包含3个单词的字符串中的前2个单词(例如)。

我的问题有以下代码。

zgood的代码的JSFIDDLE。

$('select option').each(function(i, item){
    var arr = $(item).text().split(' ');
    $(item).text(arr[0]);
});

代码运行良好,但只显示第一个单词。我试着让它显示两个单词,但我运气不好。所以,如果有人能告诉我如何让它显示我字符串的前两个单词,那就太好了。

您可以使用Array.prototype.sliceArray.prototype.join方法:

$('select option').text(function(_, currentText) {
    return currentText.split(' ').slice(0, 2).join(' ');
});

您也可以使用regex 执行同样的操作

$('select option').each(function(i, item){
    var text = $(item).text();
    var regex = /'w+'s+'w*/
    var groups = text.match(regex) || [];
    $(item).text(groups[0]);
});

这是演示