Home Web DevelopmentJavaScript JavaScript “sub-string”

JavaScript “sub-string”

Strings are frequently used in everyday programming. Fortunately, JavaScript has many built-in methods that assist us when working with arrays, strings, and other data types. These methods can be used for various tasks such as searching, replacing, concatenating strings, etc.

Data manipulation is an essential component of any online application. In addition, different methods for parsing and extracting data are available in JavaScript.

What is a JS substring?

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

One of the most popular actions in JavaScript is extracting a substring from another string. substring(), substr(), and slice() are JavaScript methods for extracting strings from a bigger one.

We’ll learn how to get a substring using the three distinct built-in methods in this article.

The substring( ) Method

Let’s have a look at the substring() technique first.

  • This technique extracts a portion of the original string and replaces it with a new string
  • Two parameters are required by the substring method
  • substring() is supported by all browsers and is an ES1 feature of JavaScript introduced in 1997
  • The substring() function pulls characters from a string and returns the substring between two indices (positions)
  • The substring() method removes characters from the beginning to the end of a string (exclusive)
  • The original string is not changed by the substring() technique
  • If the start is bigger than the end, the two arguments will be swapped, (4, 9) = (9, 4)
  • Start and end are considered as 0 if they are less than 0

Some other considerations:

The substring method results in an empty string if startIndex = endIndex. It returns an empty string if startIndex and endIndex are greater than the length of the string.

Example:

let text = "Hello Codeunderscored!";
console.log(text.substring(24, 30))
start and last index are greater than the string
start and last index are greater than the string

Substring Syntax

string.substring(start, end)

Now, let’s define the parameters in the above syntax.

Start

  • Required
  • It indicates the starting point where to begin extraction. Usually, index 0 is the index for the first character.

End

  • It is optional to have the end parameter
  • This position indicates the stopping point of the extraction. Though, it usually is up to this value but not inclusive. On the off chance that it is omitted, then it is the rest of the string.

It is vital to note that the substring in JavaScript has a return value representing the new string having the extracted characters.

As shown in the example below, any value not a number (NaN) is treated as zero.

const str = "Codeunderscored is simply scaling the heights!";
console.log(str.substring('start', 3));
non number is treated as a zero
non-number is treated as a zero

The argument ‘start’ in the above example is not a number. As a result, the generated string starts at position zero of str. In addition, the substring() function returns a copy of the string it acts on if no arguments are supplied and both parameters are omitted.

Example 1: extract string starting from 3rd position

let text = "Hello Codeunderscored!";
console.log(text.substring(3));
starting from 3rd position
Example 1: starting from 3rd position

Example 2: substring when the starting point is greater than the end

If startIndex is more than endIndex, the substring method swaps the arguments and returns a substring, presuming endIndex is greater than startIndex.

let text = "Hello Codeunderscored!";
console.log(text.substring(30, 4))
substring when the starting point is greater than the end
substring when the starting point is greater than the end

Example 3: In case the starting point is negative ( less than 0), reset start index to 0:

let text = "Hello Codeunderscored!";
console.log( text.substring(-2));
substring if the starting point is negative
substring if the starting point is negative

Example 4: extract the first value from a string

let text = "Hello Codeunderscored!";
console.log( text.substring(0, 1));
extract the first value from  a string
extract the first value from a string

Example 5: How to extract the last value in the given string

let str = "Hello Codeunderscored!";
console.log(str.substring(str.length – 1));
extract the last character in a string
extract the last character in a string

The substr() method

According to Mozilla’s documentation, the substr() method is a legacy function that should not be used. However, we’ll explain what it does because it may appear in some earlier projects, or you may find a use for it.

The substr() method returns a substring of the original string and requires the following two parameters:

string.substr(startIndex, length);
  • startIndex: indicates the substring length’s starting point
  • length: the total amount of characters that must be included (optional)

The difference with substring() is that the substr() method expects a length instead of an endIndex as the second parameter:

const myString = "I am learning JavaScript on Codeunderscored.com, and it is cool!";

myString.substr(2,4)
example of how to use substr
example of how to use substr

This example counts four characters beginning with the supplied startIndex(2) and returns them as a substring.

If the second parameter isn’t defined, it returns up to the end of the original string (much as the previous substring method). Below is an example.

const myString = "I am learning JavaScript on Codeunderscored.com, and it is cool!";

myString.substr(4)
using substr when only one parameter is provided
using substr() when only one parameter is provided

slice() method

Similar to the substring() method, the slice() method returns a substring of the original string. Further, the same two parameters are required by the slice method:

string.slice(startIndex, endIndex);
  • startIndex: denotes the beginning of the substring.
  • endIndex: it is the substring’s termination point and is optional most of the time.

Similarities between the substring() and slice() methods

The following are some of the similarities between the substring() and slice() methods.

We get a substring starting from the specified index number until the end of the original text if we don’t set an ending index as shown below.

const myString = "I am learning JavaScript on Codeunderscored.com, and it is cool!";

myString.slice(14)
providing one parameter to the slice method
providing one parameter to the slice method

If we set both the startIndex and endIndex, we’ll obtain the characters in the original text between the specified index numbers:

const myString = "I am learning JavaScript on Codeunderscored.com, and it is cool!";

myString.slice(2, 14)
providing a start and end index to the slice method
providing a start and end index to the slice method

An empty string is returned if startIndex and endIndex are larger than the length of the string.

Differences between slice() and other methods:

An empty string is returned by the slice() method if startIndex > endIndex.

const myString = "I am learning JavaScript on Codeunderscored.com, and it is cool!";
slice method returns an empty string if start index is greater than end index
slice method returns an empty string if the start index is greater than the end index

If startIndex is a negative value, the first character in the string is read from the end (reverse):

const myString = "I am learning JavaScript on Codeunderscored.com, and it is cool!";

myString.slice(-5)
supplying a negative parameter to the slice method
supplying a negative parameter to the slice method

Summary

These are the three methods for obtaining a substring in JavaScript. They consist of substring(), substr(), and slice() methods used for extracting strings from a bigger one.

substring() is a built-in JavaScript function that returns a portion of a string from a start index to an end index. Herein, the indexing process begins at zero. Essentially, substring() is used to return a string segment, starting at the supplied index and continuing for a specified number of characters after that.

Other built-in methods in JavaScript come in handy when dealing with various aspects of programming like the slice() and substr().

We hope you found this helpful article. If so, share with us your thoughts.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More