Press ESC to close

JavaScript split

0 1857

The JavaScript split method iallows you to split a string based on a separator, save the sub-strings obtained in an array and then return the array thus formed.

The syntax of this method is as follows: string.split(separator, limit).

Where string therefore represents the string to be divided. The separator parameter is mandatory and indicates which element to use to perform the division (for example, a blank space, a comma, a dash). The limit parameter is optional and represents the number of subdivisions to be made. Therefore items that go beyond this limit will not be included in the split.

This method is supported on all browsers.

JavaScript split – first example

Let’s now make some simple examples of use.

So we take a simple sentence as input and then with the split method we divide it using space as a separator element.

So here’s the complete code using JavaScript’s split method:



var coding = 'Programming helps the development of logical thinking';
var codingSplit = coding.split(' ');
console.log(codingSplit);

In the browser console we will display an array of 7 elements, as shown below:

Array (7) [“Program”, “help”, “it”, “development”, “of”, “thought”, “logical”]

N.B. Be careful to insert empty spaces between quotes. In fact, if for example we had written:



var coding =  'Programming helps the development of logical thinking';
var codingSplit = coding.split('');
console.log(codingSplit);

As a result we would have obtained the subdivision by letter and therefore in our case an array of 49 elements:

Array (49) [“P”, “r”, “o”, “g”, “r”, “a”, “m”, “m”, “a”, “r”, …]

JavaScript split – second example

Let’s change the sentence, adding a second thought after the comma, as in the example below:



var coding = 'Programming helps the development of logical thinking, let's have fun learning JavaScript';

var codingSplit = coding.split(',');
console.log(codingSplit);

As a result we will see in the browser console an array of 2 elements:

Array [“Programming helps the development of logical thinking”, “let’s have fun learning JavaScript”]

Conclusion

In this lesson we studied the JavaScript split method we use to split a string and save the various parts in an array.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript variables and costants

Other stories

JavaScript indexOf

Next Story

JavaScript Trim

Previous Story