从括号中取出字符串并放入数组以组织

时间:2018-03-28 18:55:13

标签: jquery arrays timer split

我正在尝试构建一个计时器,我会根据用户输入的字符串显示最新的更新。

示例字符串:

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]

2 个答案:

答案 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;
&#13;
&#13;

编辑:以下评论的解决方案:

&#13;
&#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;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用exec()slice()的组合来获得所需的结果。

var str = "Shawn [Samson] arriving on [3/28/18 5:43 PM]",
capturedData = (/.+(\[.+\]).+(\[.+\])/).exec(str).slice(1, 3);
console.log(capturedData);