didn't find the solution in SPLIT function.. i was trying to convert a string into array.. String is like.
My name-- is ery and your-- is this
i just want to convert that string to array, and then print it out but while getting this '-- ' break the line too.
i have did that so far
function listToAray(fullString, separator) {
var fullArray = [];
if (fullString !== undefined) {
if (fullString.indexOf(separator) == -1) {
fullAray.push(fullString);
} else {
fullArray = fullString.split(separator);
}
}
return fullArray;
}
but is for Comma separated words in string, but what i want is to just convert string to array and then print it out while breaking line on getiing '-- ' this is array Thanks in advance
-
1The question title mentions the other way round.emerson.marini– emerson.marini2014年09月03日 10:34:16 +00:00Commented Sep 3, 2014 at 10:34
3 Answers 3
seems to work :
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,"--"));
console output:
["My name", " is ery and your", " is this"]
what do you expect ?
1 Comment
fullArray = fullString.split(separator); inside the if statement because if separator is not in the string the split function will convert the string into an array anywayWhy are you doing all that complicated stuff man? There is a .split() method that allows you to do that in a single line of code:
text = "My name-- is ery and your-- is this";
array = text.split('--');
> ["My name", " is ery and your", " is this"]
Now if you want to break line on -- then you can do the following:
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"
Comments
You can use the split method:
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"]