How to Split a String in Javascript Easily? – 2 Methods

Splitting a string in Javascript is quite easy. However, it can be a little confusing sometimes. If you’re using javascript for a while, I think you already know that javascript language can be weird sometimes. Here I am going to show you “How to Split a String in Javascript Easily?“(some of the easiest ways).

Before we get into the main topic, let us few things about string and javascript. I think you already know about the basics of string and JS.but still, I have to cover those topics. This is a quick tutorial.

What is String in Javascript?

A Javascript string consists of a series or sequence of characters. A string is a primitive data type in javascript. 

Just an array, strings indexes in javascript are also zero-index based. The first character in a string would be at index 0, the second character at index 1, and so on. 

How to Create a String in Javascript?

There are mainly three ways to create a string – 

  1. Single quotes: ‘This is a demo string with single quotes.’

  2.  Double quotes: “A string using double-quotes. “

  3. Backticks / Template literals: `A string using Backticks.`

Example with usage

let str1 = 'string 1';
let str2 = "string2";
let concatenation = `first string ${str2}, second string {str2}`;

Generally, single quotes and double quotes are used to represent strings. Backticks help us to include variables or expressions into a string by using $ sign or ${variable or expression}.

How to Split a String in Javascript?

There are many ways to split a string in javascript, but we are going to focus on the String split() Method and slice() method. 

Also Read : The Big O Notation Explained-Examples of Big O Notation

How to Split a String in Javascript Using The Split() Method?

We use the split() method to split a specific string into an array of substrings. I am going to show you different ways to turn a string into an array (or splitting a string) using the split() method.

| Syntax: string.split(separator, limit

Learn more about the split() method

How to Turn a String into a Single Array in JavaScript? 

How to Split a String in Javascript Easily
Image : Jsbin
// Code 
 const str = "a demo string ";
 const afterSplit = str.split();
 console.log(str); console.log(afterSplit);
Output:
 "a demo string " //str
["a demo string "] //afterSplit

Here, We are splitting a string into a single array or one-element array. We can easily turn any string into a single array using the split method (without any parameter).

Editor: Jsbin

Also Read : JSON in Javascript | What is a JSON file ?

How to Turn a String into an Array of Characters in JavaScript?

Some people think it is quite difficult to split a string into an array of characters in js. But in reality, it is very easy if you use the split() method.

How to Split a String in Javascript
Image : Jsbin
//Code 
  const main_str = "a demo string "; //string
  const afterSplit = main_str.split(" ");
  console.log(main_str); 
  console.log(afterSplit);
Output :
   "a demo string "
    ["a", " ", "d", "e", "m", "o", " ", "s", "t", "r", "i", "n", "g", " "]

Using an empty string as a parameter for the split() will split a string into individual array elements or an array of characters, including any whitespace or symbol (as shown above).

Editor: Jsbin

Also Read : The Big O Notation Explained-Examples of Big O Notation

How to Split a String Using a Character in js?

We are going to use the split method to an array using a specific character. All we need to do is to pass that specific character as a parameter for the split method.

Let us assume, we are going to pass a comma(,) as the parameter.

How to Split a String Using a Character in js?
Image : Jsbin

//Code 
  const main_str = "Let,us,split, string,using,comma";
  const afterSplit = main_str.split(",");
  console.log(main_str); 
  console.log(afterSplit);
Output
"Let,us,split, string,using,comma"
["Let", "us", "split", " string", "using", "comma"]

Here, we are using splitting the whole string using comma as their breakpoints. You can use a hyphen or other characters too.

Editor: Jsbin

Also Read : 10 Best NPM Packages for Beginners

How to Remove Whitespace in a String?

We can split a string without whitespace using the split method and Regex (Regular expressions)

How to Split a String in Javascript
Image:  playcode
//Code 
  const main_str = "ok i love QG ";
  const afterSplit = main_str.split("/\s/");
  console.log(afterSplit);
Output:
["ok i love QG "]

Here, we are using the regex “/\s/” to remove the whitespace. 

Editor: playcode

How to Use The Limit Parameter in Split() Method ?

Split a String in Javascript
age:  playcode

We can use the limit or second parameter to limit items returned. You can get a specific number of items using the second parameter of the split() method.

//Code
  const main_str = "qualifiedgeek";
  const afterSplit = main_str.split("",3);
  console.log(afterSplit);
Output
 ["q","u","a"]

Editor: playcode

Here, we are using the limit parameter to get only three characters or items as an array from the string above. 

How to Use slice() in javascript?

The slice() method is a handy method to extract a specific part of a string. Since the slice method returns a new string rather than an array, we can use slice() to split a string into a new string.

The slice method accepts two parameters 1. Start 2.End. The slice method uses zero-index based meaning the first character has the position 0, the second character has the position 1, and so on.

| Syntax : string.slice(start, end)

How to Split a String in Javascript
Image:  playcode
//Code 
const text1 = "This is a demo string";
const result = text1.slice(0,4);
console.log(result);

Output :

This

Editor: playcode

Learn More about JavaScript String slice()

Note: Slice returns a new string, not an array of characters.

Conclusion:
Now you know How to Split a String in Javascript. This article covered some common ways to split a string in JS. However, there are other ways to split a string in Javascript. If you know the regular expression (regex), the task becomes much easier.

Remember to learn other string methods such as indexOf(),charAt(),replace(),substr(),trim(),toUpperCase(),toLowerCase(),etc. as well. It will help you determine the methods for you. The main difference between the split() method and the slice() method is that split returns an array, whereas the slice returns a new string.

Image / screenshot :  playcode & Jsbin

Leave a Comment