/    Sign up×
Community /Pin to ProfileBookmark

Splitting an array

I thought I understood how to split an array. But, it seems that once I split it, and I want to replace each comma with a line break, that it only works for the first comma.

[CODE]var arr_errors = new Array();
arr_errors.push(‘Test1’);
arr_errors.push(‘Test2’);
arr_errors.push(‘Test3’);
arr_errors.push(‘Test4’);
var test = arr_errors.toString().replace(‘,’, ‘n’)
alert(test);[/CODE]

Why is it only replacing the first comma?

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@nnhubbardauthorApr 06.2009 — I figured it out, I needed to pass the g flag. Silly me!

[CODE].replace(/,/g, 'n');[/CODE]
Copy linkTweet thisAlerts:
@astupidnameApr 06.2009 — You are not actually doing a split, but converting to string, and instead of doing toString().replace(/,/g,'n')

You could use join() which converts to string with a specified delimiter between the array items:
var arr_errors = new Array();
arr_errors.push('Test1');
arr_errors.push('Test2');
arr_errors.push('Test3');
arr_errors.push('Test4');
var test = arr_errors.join("n");
alert(test);
×

Success!

Help @nnhubbard spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...