1

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...

Exception
  • 8,111
  • 22
  • 85
  • 136

5 Answers5

2
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);
}
Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
1

I came up with this:

str.match(/-#([A-Z]) ([a-zA-Z. ]+)/g).map(function (i) {
   return i.split(/-#([A-Z])/).splice(1)  
})

map won't work in IE 8 but there's a ton of shims. mdn docs

Example

Joe
  • 80,724
  • 18
  • 127
  • 145
1
var str = str.split("-#");
var newStr=[];
for(var i = 0; i < str.length; i++) {
    if(str[i] != "" && str[i].substr(0,7) != 'Garbage') newStr.push(str[i]);
}
console.log(newStr);

A test jsFiddle can be found here.

j08691
  • 204,283
  • 31
  • 260
  • 272
1

A regular expression exec can allow you to use a simpler pattern for the global match.

The match can include the '#Garbage' in an index that can be ignored when you build the array.

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."]
]
kennebec
  • 102,654
  • 32
  • 106
  • 127
0

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?.

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/.

Community
  • 1
  • 1
Jeff
  • 12,555
  • 5
  • 33
  • 60