Shane
Shane

Reputation: 5677

split array with delimiter into string

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

Upvotes: 0

Views: 54

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386560

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>');

Upvotes: 2

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

var arrFinal = [];

arr.forEach(function(val, key) {
        arrFinal = arrFinal.concat(val.split('(!)'))
    })


console.log(arrFinal)

Upvotes: 1

rrk
rrk

Reputation: 15846

Use join with the same delimiters.

var arr = ["abc", "stued(!)rain(!)shane", "cricket"];
alert(arr.join('(!)').split("(!)"));

Upvotes: 3

Related Questions