2012-01-18 30 views
1

我會像下面得到兩個符號之間的字符串中的字符串,並將其推到一個數組

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 arr = [["A","This text belongs to A. 
Dummy Text of A."],["B","This text belongs to B. 
Dummy Text of B."] etc...] 
標題數組的字符串

請幫我。我怎樣才能做到這一點...

+0

我假設你的引號應該在「這個字符串被忽略..」之後,而不是在「C的虛擬文本」之後。 – Jeff 2012-01-18 03:37:37

+0

@Jeff是的,我正在編輯。謝謝 – Exception 2012-01-18 03:39:34

+0

是隻有一行或「\ n」新行有嗎??? – 2012-01-18 03:44:43

回答

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

+1用於實際回答問題。 – Jeff 2012-01-18 03:46:35

+0

感謝您的回答。 「a」沒有在上面聲明。 – Exception 2012-01-18 03:51:17

+0

修正了它......「a」在鍵盤旁邊的「s」上...... – 2012-01-18 03:52:13

1

我想出了這一點:

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

地圖將不會在IE 8的工作,但有一噸墊片。 mdn docs

Example

+0

OMG ..非常感謝..驚奇的看着這段代碼 – Exception 2012-01-18 03:56:08

+0

這是刪除字符串中的新行。請使用這個小提琴。我很容易爲您編輯。 – Exception 2012-01-18 04:03:01

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

測試的jsfiddle可以發現here

1

正則表達式exec可以允許您爲全局匹配使用更簡單的模式。

匹配可以在構建數組時可以忽略的索引中包含'#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."] 
] 
相關問題