Ryan
Ryan

Reputation: 10049

Explode string and make a line break after each word

I have a textbox (I usually call it like this: document.forms[0].text.value) that has this kind of value:

a,b,c,d,e,f,g,etc

what I want to do is "explode" (like the php function) on each of the commas in the above string, then put it back into the textbox so I end up with this:

a
b
c
d
e
f
g
etc

Doing a little Googling I see I will need to use split() but doing something like:

st.split(",") + "<br />";

is giving me nothing but invalid results.

Upvotes: 3

Views: 14830

Answers (3)

Muhammad Naeem
Muhammad Naeem

Reputation: 1

    var string = "University of USA";
    string =  string.split('').join('<br>');

Upvotes: -2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

Either:

st.split(",").join("\n");

or:

st.replace(/,/g,"\n");

Since you're putting it in a textarea, by the look of things, you need newlines, not BR tags.

Upvotes: 15

Adam Mihalcin
Adam Mihalcin

Reputation: 14478

You are right in saying that

st.split(",")

will split st into an array of the substrings you are looking for. However, you want to put each substring onto its own line, not one line for all the substrings. So, you need

st.split(",").join("<br />")

to place a br tag in between each of the substrings and thus put each on its own line.

Upvotes: 3

Related Questions