从字符串中获取第二个和第三个单词

从字符串中获取第二个和第三个单词

本文介绍了从字符串中获取第二个和第三个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jQuery中有字符串:

I have strings in jQuery:

var string1 = 'Stack Exchange premium';
var string2 = 'Similar Questions'; //  only two
var string3 = 'Questions that may already have your answer';

我如何从第二个和第三个单词中得到答案?

How can i get from this second and third words?

var second1 = ???;
var third1 = ???;
var second2 = ???;
var third2 = ???;
var second3 = ???;
var third3 = ???;

推荐答案

首先,您没有在jQuery中"的字符串和变量.jQuery与此无关.

First, you don't have strings and variables "in jQuery". jQuery has nothing to do with this.

第二,更改您的数据结构,如下所示:

Second, change your data structure, like this:

var strings = [
    'Stack Exchange premium',
    'Similar Questions',
    'Questions that may already have your answer'
];

然后使用第二个和第三个单词创建一个新的数组.

Then create a new Array with the second and third words.

var result = strings.map(function(s) {
    return s.split(/\s+/).slice(1,3);
});

现在您可以像这样访问每个单词:

Now you can access each word like this:

console.log(result[1][0]);

这将为您提供第二个结果的第一个单词.

This will give you the first word of the second result.

这篇关于从字符串中获取第二个和第三个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:40