我正在尝试构建一个计时器,我会根据用户输入的字符串显示最新的更新。
示例字符串:
var text = "Shawn [Samson] arriving on [3/28/18 5:43 PM]";
所以我试图提取括号括起来的任何信息,将其存储到数组中,然后找到最接近的时间并在计时器中显示。
我是如何尝试在括号中输入字符串的:
var abc = text.slice(text.indexOf('[') +1,text.indexOf(']'));
但它只返回a
我将从表格中提取的一个例子:
Shawn [Samson] arriving on [3/28/18 5:43 PM]
Shawn [Jones] arriving on [3/29/18 5:43 AM]
Shawn [Simms] arriving on [3/28/18 5:43 PM]
Shawn [Samson] arriving on [3/28/18 10:43 PM]
答案 0 :(得分:0)
要处理单个字符串:
var text = "Shawn [Samson] arriving on [3/28/18 5:43 PM]";
var regex = /\[([^\]]+)\]/g;
var tmp;
do{
tmp = regex.exec(text);
if(tmp){
console.log(tmp[1]);
}
}while(tmp);

迭代字符串数组并存储数据:
var texts = [
"Shawn [Samson] arriving on [3/28/18 5:43 PM]",
"Shawn [Jones] arriving on [3/29/18 5:43 AM]",
"Shawn [Simms] arriving on [3/28/18 5:43 PM]",
"Shawn [Samson] arriving on [3/28/18 10:43 PM]"
]
var results = [];
var regex = /\[([^\]]+)\]/g;
var tmp;
for(var i = 0, j = 0; i < texts.length; i++){
results[j] = [];
do{
tmp = regex.exec(texts[i]);
if(tmp){
results[j].push(tmp[1]);
}
}while(tmp);
j++;
}
console.log(results);
&#13;
编辑:以下评论的解决方案:
var texts = "Shawn [Samson] arriving on [3/28/18 5:43 PM]Shawn [Jones] arriving on [3/29/18 5:43 AM]Shawn [Simms] arriving on [3/28/18 5:43 PM]Shawn [Samson] arriving on [3/28/18 10:43 PM]";
var results = [],
regex = /\[([^\]]+)\]/g,
i = 0, j = 0,
tmp;
results[0] = [];
do{
tmp = regex.exec(texts);
if(tmp){
results[j].push(tmp[1]);
}
if(i%2 != 0){
j++;
results[j] = [];
}
i++;
}while(tmp);
results.splice(-1,1);
console.log(results);
&#13;
答案 1 :(得分:0)