header ad

Javascript substring


We frequently work with strings in our regular programming. Fortunately, JavaScript includes a number of built-in functions for working with arrays, strings, and other data types. These methods can be used to do a variety of tasks, such as finding, replacing, and concatenating strings.

One of the most popular actions in JavaScript is extracting a substring from a string. You’ll learn how to get a substring using three distinct built-in methods in this tutorial. But first, let me define a substring in a few words.

header ad

What is a Substring?

A substring is a string that is a part of another string:

"I am learning JavaScript and it is very easy!"  -->  Original String

"I am learning JavaScript"  -->  Substring

"JavaScript is easy!"  -->  Another Substring

In some circumstances, such as in the example above, we need to extract one or more substrings from an entire sentence or paragraph. Now let’s look at three different approaches to implement it with JavaScript.

The substring( ) Method

Let’s have a look at the substring() method first. This technique just extracts a portion of the original string and replaces it with a new string. Two parameters are required by the substring method:

string.substring(startIndex, endIndex);
  • startIndex: indicates where the substring begins.
  • endIndex: represents the substring’s end point (optional)

Let’s look at an example of how to use it. Assume we have the following example string:

const myString = "I am learning JavaScript substring and it is cool!";

Read More Blogs

Leave a Comment

Your email address will not be published.