How to Trim Substring in JavaScript

There are the following ways to trim a substring in JavaScript.

  1. replace(): This method helps to remove a particular substring from a given string.
  2. substr(): This method helps extract the substring from a given string.

Method 1: Using the replace() function

To trim a substring in JavaScript, you can use the “string.replace()” method. The string.replace() is a built-in method that searches a string for a value or a regular expression. It returns a new string instead of changing the original string.

Syntax

String.replace(specificValue, newValue)

Arguments

searchValue:

It is required, This is a required argument for the given function. This defines the element that needs to be searched for.

requiredValue:

Another required argument for the given function. This is the element with which the searchValue is to be replaced.

Return value:

It returns a string.

Example

let ourWord = "This is Old String";
let ourNewWord = ourWord.replace("Old", "");
console.log(ourNewWord)

Output

This is String

In this example, we want to trim an “Old” substring with some “” empty substring by using the replace() function and assigning the new string to a new string variable. And then, we display the new string using the console.log() method.

Method 2: Using the substr() function

The substr() is a built-in JavaScript method that extracts the specific part of a given string. The substr() function takes two parameters: startIndex and length of the extracting string.

Syntax

String.substr(startIndex, length)

Arguments

start: 

This is a required argument. This defines the start position. Usually, in most programming languages, including javascript, the indexing starts with 0. 

The following two special cases are associated with the argument:

  1. First, if the entered start value is greater than the length of the string, then the given function will return “”, which is an empty string. Second, on the hand, if the start is  a negative number, the counting starts from the end of the string, i.e., reverse.

length:

This parameter defines the number of extracted parts. If this parameter is not passed, it extracts all the parts of the string starting from the start position defined by the user.

Return value

It returns a string containing the extracted part. The function can also return an empty string.

Example

let ourWord = "This is Old String.";
let ourNewWord = ourWord.substr(8, 3);
console.log(ourNewWord)

Output

Old

In this example, we use the substr() function, which extracts the substring starting from index 8 up to 3 lengths. Then, as an output, we get “Old” displayed on the console using the console.log() function.

Leave a Comment