2014-09-03 49 views
1

未在SPLIT函數中找到解決方案.. 我試圖將字符串轉換爲數組.. 字符串就像。將數組轉換爲字符串Javascript

My name-- is ery and your-- is this 

我只是想將該字符串轉換爲數組,然後打印出來,但同時得到這個' - '也破壞了行。

我已經做了,到目前爲止

function listToAray(fullString, separator) { 
    var fullArray = []; 

    if (fullString !== undefined) { 
    if (fullString.indexOf(separator) == -1) { 
     fullAray.push(fullString); 
    } else { 
     fullArray = fullString.split(separator); 
    } 
    } 

    return fullArray; 
} 

,但對於在逗號分隔字符串的話,但我想要的是隻是轉換字符串數組,然後打印出來,而在getiing打破線「 - 「這是數組 預先感謝

+1

的問題標題提到了另一種方式。 – melancia 2014-09-03 10:34:16

回答

1

似乎工作:

text = "My name-- is ery and your-- is this"; 


function listToAray(fullString, separator) { 
    var fullArray = []; 

    if (fullString !== undefined) { 
    if (fullString.indexOf(separator) == -1) { 
     fullAray.push(fullString); 
    } else { 
     fullArray = fullString.split(separator); 
    } 
    } 

    return fullArray; 
} 


console.log(listToAray(text,"--")); 

控制檯輸出:

["My name", " is ery and your", " is this"] 

你期望什麼?

+0

實際上,在if語句中只能使用'fullArray = fullString.split(separator);'因爲如果separator不在字符串中,'split'函數會將字符串轉換爲數組 – sergiomse 2014-09-03 10:38:22

0

可以使用split方法:

var str = "My name-- is ery and your-- is this"; 
var res = str.split("--"); 
console.log(res); 

// console output will be: 

["My name", " is ery and your", " is this"] 
0

你爲什麼要盡一切複雜的東西的人嗎?有一個.split()方法,可以讓你做,在一個單一的代碼行:如果你想打破--線,那麼你可以做以下

text = "My name-- is ery and your-- is this"; 
array = text.split('--'); 

> ["My name", " is ery and your", " is this"] 

現在:

text = "My name-- is ery and your-- is this"; 
list = text.replace(/\-\-/g, '\n'); 
console.log(list); 

> "My name 
    is ery and your 
    is this"