JavaScript

JavaScript String Split Example

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. In these cases, JavaScript string split functions come to the rescue. You can split the long string into small ones and save them as an array.

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:

nameArray=['Anne','Ben','Cindy','Diane','Era'];

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.

This is how you split or join strings using JavaScript.

Download the source code

This was an example of string split in JavaScript.

Download
Download the full source code of this example here: StringSplit

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
noor syed
9 years ago

that was cool Era

Back to top button