javascript - 循环遍历字符串

标签 javascript string split

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

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);
}

我该怎么做?!

最佳答案

最简单的事情可能是使用正则表达式查找“​​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 border"] 认为- 是您可能不想要的边界;并且单独地,您对“单词”的定义可能与 [^\s]+ 等不同)。

关于javascript - 循环遍历字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51708818/

相关文章:

javascript - 如何检测 Javascript 正则表达式中的命名空间字符串?

javascript - 查找表行时,不让嵌套的表头行停留在Javascript函数中

javascript - 滚动动画在移动设备上无法像在桌面滚动上一样工作。Top() jQuery

java - 使用分隔符和hasNext在java中获取int用户输入?

java - 如何将句子拆分为单词,同时保留一些包含空格的复合表达式?

javascript - Tiptap (Prosemirror) 提及标签的协作模式错误

algorithm - 他们如何在字符串中搜索

Javascript |将字符串变量传递给 onclick 事件不起作用

java - 如何从基于斜杠的分区中排除单字符表达式?

Python:如何分割字符串但保留非字母数字字符