2015-12-25 38 views
2

我剛剛在我想要在;或換行符每次出現分裂的字符串的情況。我想確保這不會留下任何空的數組元素,所以我決定使用正則表達式儘可能包含一個字符串。使用/和/ [AB]/JavaScript中分裂()的正則表達式

我第一次使用foo.split(/(\n|\r|;)+/)嘗試,但這種奇怪的預期與雙輸入沒有工作。使用(據我所知)相同的語法foo.split(/[\n\r;]+/)沒有按預期工作,但。

下面是一個例子:

var foo = "test;\nexample;\n\ndouble enters;\nand without semicolon\nend;\n"; 
 
console.log(foo.split(/[\n\r;]+/)); 
 
console.log(foo.split(/(\n|\r|;)+/)); 
 
//and to show that the matching strings are indeed equal: 
 
console.log(foo.match(/[\n\r;]+/g)); 
 
console.log(foo.match(/(\n|\r|;)+/g)); 
 

 
document.write('<pre>'+foo+'</pre>'); //demonstrating what the string looks like.

所以你可以在你的控制檯中看到的,如果你運行的片段中,正則表達式應該是相同的位置,因爲他們match()確切相同的字符。分割字符串時的輸出雖然完全不同。

同樣例如替換爲A上的匹配的字符和B時(其中A爲B替換所有換行符,分號)出錯。即使這樣,這2個正則表達式分割也會有不同的結果。

所以我的問題是:有誰知道是什麼原因導致這種神祕的行爲?

回答

2

這是因爲當您使用捕獲組與.split()方法中,捕獲組的匹配的內容被包括在結果數組英寸

MDN

如果隔膜含有捕獲括號,匹配的結果在陣列中返回。

如果使用非捕獲組,結果將是相同的:

foo.split(/(?:\n|\r|;)+/) 

實施例:

var foo = "test;\nexample;\n\ndouble enters;\nand without semicolon\nend;\n"; 
 
console.log(foo.split(/[\n\r;]+/)); 
 
console.log(foo.split(/(?:\n|\r|;)+/)); 
 
//and to show that the matching strings are indeed equal: 
 
console.log(foo.match(/[\n\r;]+/g)); 
 
console.log(foo.match(/(\n|\r|;)+/g));