When building or maintaining an interactive website, it may happen that the input you get from the user can be correct in meaning, but written as a long string separated by special characters such as commas or semicolons.
Here’s how you can do that.
The split() method
You can split a string using the
split() method. It takes a delimiter as a variable, which can be either a comma, a semicolon, a quotation mark, or whatever special character that is used to separate the string. You can use it like this:
var namelist = "Anne,Ben,Cindy,Diane,Era "; var nameArray = namelist.split(',');
First, we have declared a string variable which contains some random names (you can use whatever string you want). Then we used the
split() method on the string, by placing a comma as a delimiter. That means that the string will be divided into one more string than the number of the commas, and these will be respectively the strings before and after each comma. The result of the previous example will be this:
The delimiter argument to this method is optional, which means that if you leave it blank, the method will split the string after it finds a NULL character. Practically, it means that your string will not be divided.
The join() method
What is often called the reverse of the
split() method is the
join() method. It is used to put together into one single string the elements of an array, using a delimiter as a joint. The code snippet below will show you how exactly it is used:
var array = ['This','is','an','apple.']; var sentence= array.join(' ');
We have declared and given string values to an array, and then used the
join() method on this array to turn it into a single string, using a blank space as a joint.
The result will be this:
sentence="This is an apple.";
If you omit the joint character in this method, a comma will be used instead.
Download the source code
Download the full source code of this example here: StringSplit