How to split a string? JavaScript essentials

/ #JavaScript


Splitting a string using JavaScript is something you do from time to time. But it's easy to forget the syntax, here's how you can split a string.

Why should I split a string?

Splitting strings can be used for a lot of different purposes. Maybe you want to read a sentence word by word or read a word letter by letter.

The point is that there is a lot of different things you need this for and it's easy to forget the syntax if you don't use it often.

A simple example

var str = "This is a sentence.";
var splitted = str.split(" ");

You should now have an array with four elements (['This', 'is', 'a', 'sentence.']). You can now access one of the values, iterate over them reverse them, etc.

Splitting with a limit

Let's say that we have the same sentence (This is a sentence.) and you want to split it and get the two first words.

var str = "This is a sentence.";
var splitted = str.split(" ", 2);

As you can see, the code is very similar, but we passed in another parameter (2). If you print out the "splitted" array now, you should see two elements: ['This', 'is']

Separators

You can use what ever you want as the separator. It can be a space, a letter, a sign, multiple letters, etc. And you can even leave it blank. If you leave it blank, it will split the string between each character.

Other relevant JavaScript tutorials

How to replace a string
How to check if a string starts with a certain word


Comments

No comments yet...

Add comment

Subscribe to my newsletter