Easy JavaScript Tutorial: Splitting a string with JavaScript



When we create a variable in JavaScript with string value, in fact this variable contains arrays, each string character inside one array element.

For example, let’s create a string variable var myString = "Hello!";. Then if you run this code: myString.length it will return “6” as it’s value, that means that variable contains 6 array elements, which is 6 characters.

There is built in function we can use to split a string into several parts depends on our need. For example, let’s create this variable var newString = "Hello, world!";. Now we want to split that “Hello, world!” into two parts “Hello” and “world!” (separated by “,”). What we’re going to do is to use this built in function: newString.split(","); and what happens next is that variable now contains two array elements, first “Hello” and the second ” world!” (with white space, of course).

Watch the tutorial here:

loading...