我希望得到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);
}
我该怎么做呢?!
最简单的事情可能是使用正则表达式查找“和”后跟空格后面跟着“单词”,例如像/\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 boundary”]认为-
是您可能不需要的边界;并且单独地,您对“word”的定义可能与[^\s]+
等不同。)。
首先,您需要将整个字符串拆分为“和”,然后必须将给定数组的每个元素拆分为空格,第二个给定数组的第一个元素将是“和”字后面的第一个单词。
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]);
}
您可以拆分,检查“和”字,并获得下一个:
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++;
}
另一种使用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))