2014-09-03 246 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"