Home / javascript / Split a JavaScript string into words.

Split a JavaScript string into words.

To split a JavaScript string into words, you can use the split() method, which divides a string into an array of substrings based on a specified separator. If you want to split the string into words, you can use a regular expression as the separator to split the string wherever there are spaces or other whitespace characters. Here’s an example:

const sentence = "This is a sample sentence";
const words = sentence.split(/\s+/);


In this example, \s+ is a regular expression that matches one or more whitespace characters (spaces, tabs, newlines, etc.). So, the split() method will split the string sentence into an array of words wherever there are one or more whitespace characters.

The output will be:

["This", "is", "a", "sample", "sentence"]

Each element of the resulting array will contain one word from the original string.

About admin

Check Also

What are the differences between var, let and const in JavaScript?

var, let, and const are all used for variable declaration in JavaScript, but they have …

Leave a Reply

Your email address will not be published. Required fields are marked *