I have an array like below
["abc", "stued(!)rain(!)shane", "cricket"]
How can i convert this to string by spliting on (#) like below:
"abc"
"stued"
"rain"
"shane"
"cricket"
Below is the code i have tried
var arr = ["abc", "stued(!)rain(!)shane", "cricket"];
console.log(arr.join('').split("(!)"));
I am getting abcstued,rain,shanecricket which is not the desired output
asked Feb 4, 2016 at 18:05
Shane
5,70116 gold badges58 silver badges82 bronze badges
3 Answers 3
Use join with the same delimiters.
var arr = ["abc", "stued(!)rain(!)shane", "cricket"];
alert(arr.join('(!)').split("(!)"));
answered Feb 4, 2016 at 18:06
rrk
15.9k4 gold badges32 silver badges49 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
This is missing, a solution with Array#reduce:
var arr = ["abc", "stued(!)rain(!)shane", "cricket"],
result = arr.reduce(function (r, a) {
return r.concat(a.split('(!)'));
}, []);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
answered Feb 4, 2016 at 18:13
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
2 Comments
Shane
What is 0, 4 there in JSON.Stringify()
Nina Scholz
that is the replace and the spaces --> developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
var arrFinal = [];
arr.forEach(function(val, key) {
arrFinal = arrFinal.concat(val.split('(!)'))
})
console.log(arrFinal)
answered Feb 4, 2016 at 18:10
RIYAJ KHAN
15.3k5 gold badges34 silver badges56 bronze badges
Comments
lang-js