遍历字符串

时间:2018-08-06 13:29:54

标签: javascript string split

我想获取单词and之后显示的每个单词。

var s = "you have a good day and time works for you and I'll make sure to 
get the kids together and that's why I was asking you to do the needful and 
confirm"

for (var  i= 0 ; i <= 3; i++){
    var body = s;
    var and = body.split("and ")[1].split(" ")[0];
    body = body.split("and ")[1].split(" ")[1];
    console.log(and);
}

我该怎么做?!

4 个答案:

答案 0 :(得分:1)

最简单的方法可能是使用正则表达式查找“​​ and”,后跟空格,后跟“ word”,例如/\band\s*([^\s]+)/g

var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm";
var rex = /\band\s*([^\s]+)/g;
var match;
while ((match = rex.exec(s)) != null) {
  console.log(match[1]);
}

您可能需要稍微调整一下(例如,\b [“单词边界”]认为-是您可能不希望使用的边界;另外,您对“ word”的定义“可能与[^\s]+等不同。)

答案 1 :(得分:0)

首先,您需要将整个字符串拆分为“ and”,之后,您必须将给定数组的每个元素拆分为空格,第二个给定数组的第一个元素将是“ and”之后的第一个单词字。

  var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm"


        var body = s;
        var and = body.split("and ");
        for(var i =0; i<and.length;i++){
        console.log(and[i].split(" ")[0]);
        }

答案 2 :(得分:0)

您可以拆分,检查“ and”一词,然后得到下一个:

var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm";
var a = s.split(' ');
var cont = 0;
var and = false;

while (cont < a.length) {
  if (and) {
    console.log(a[cont]);	
  }
  and = (a[cont] == 'and');
  cont++;
}

答案 3 :(得分:0)

使用replace

的另一种方法
var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm"

s.replace(/and\s+([^\s]+)/ig, (match, word) => console.log(word))