[英]Get the string between two symbols in a string and push them to an array
I will have a string like below 我将有一个如下所示的字符串
var str = "-#A
This text belongs to A.
Dummy Text of A.
-#B
This text belongs to B.
Dummy Text of B.
-#C
This text belongs to C.
Dummy text of C.
-#Garbage
This string should be ignored"
I want an array like below ignoring text heading with "Garbage" 我想要一个像下面这样的数组,忽略带有“垃圾”的文本标题
var arr = [["A","This text belongs to A.
Dummy Text of A."],["B","This text belongs to B.
Dummy Text of B."] etc...]
Please help me on this. 请帮我。 How can I make it done... 我该怎么做...
var str="...";
var ar=str.split('-#');
var res=new Array();
for (var s in ar) {
if (s=='') continue;
var b=ar[s].split('\n');
var name=b.shift();
if (name=='Garbage') continue;
b=b.join('\n');
res[res.length]=new Array(name,b);
}
A regular expression exec can allow you to use a simpler pattern for the global match. 正则表达式exec可以允许您为全局匹配使用更简单的模式。
The match can include the '#Garbage' in an index that can be ignored when you build the array. 该匹配项可以在构建数组时将其忽略的索引中包含“ #Garbage”。
var str= "-#A This text belongs to A. Dummy Text of A.-#B This text belongs to B. Dummy Text of B.-#C This text belongs to C. Dummy text of C.-#Garbage This string should be ignored"
var M, arr= [], rx=/-#((Garbage)|(\w+)\s*)([^-]+)/g;
while((M= rx.exec(str))!= null){
if(M[3]){
arr.push(['"'+M[3]+'"', '"'+M[4]+'"']);
}
}
// arr>>
// returned value: (Array)
[
["A", "This text belongs to A. Dummy Text of A."],
["B", "This text belongs to B. Dummy Text of B."],
["C", "This text belongs to C. Dummy text of C."]
]
What you're looking for are capture groups. 您正在寻找的是捕获组。 When you have a regex that matches the appropriate section, you can use a capture group to grab that section and put it into an array. 当您拥有与适当部分匹配的正则表达式时,可以使用捕获组来获取该部分并将其放入数组中。 See the answer for How do you access the matched groups in a JavaScript regular expression? 请参阅如何在JavaScript正则表达式中访问匹配的组的答案。 . 。
If you don't know how to use regex at all, you should look for a tutorial on it, and try some, so that you can get a more specific question and so that you can answer http://whathaveyoutried.com/ . 如果您根本不知道如何使用正则表达式,则应该在上面寻找一个教程,然后尝试一下,以便获得更具体的问题,并可以回答http://whathaveyoutried.com/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.