Tuesday, September 24, 2024
Google search engine
HomeLanguagesJavascriptDifference between substr() and substring() in JavaScript

Difference between substr() and substring() in JavaScript

In JavaScript Both of the functions are used to get the specified part of the string, But there is a slight difference between them. substr() and substring() are string methods used to extract parts of a string. The main difference is that substr() accepts a length parameter, while substring() accepts start and end indices.

JavaScript str.substr() Function: The str.substr() function returns the specified number of characters from the specified index from the given string.

Syntax:

str.substr(start, len)

Example: This example uses only one parameter for both functions and produces the same output. 

Javascript




const str1 = "GeeksForGeeks";
const substrResult = str1.substr(7);
const substringResult = str1.substring(7);
 
console.log("Str.substr(7) =", substrResult);
console.log("Str.substring(7) =", substringResult);


Output

Str.substr(7) = rGeeks
Str.substring(7) = rGeeks

JavaScript str.substring() Function: This function gets the characters from a string, between two specified indices, and returns the new string.

Syntax:

str.substring(start, end)

Example: This example uses the parameter (3, 7) for both functions and returns the output. 

Javascript




const str1 = "GeeksForGeeks";
const substrResult = str1.substr(3, 7);
const substringResult = str1.substring(3, 7);
 
console.log("Str.substr(3, 7) =", substrResult);
console.log("Str.substring(3, 7) =", substringResult);


Output

Str.substr(3, 7) = ksForGe
Str.substring(3, 7) = ksFo

Let us understand the differences in a tabular form:

JavaSscript substr() Function

JavaScript substring() Function

It is used to extract a part of the string

It is used to extract the specified substring within a string

It takes parameters as starting index of the part which we want to extract and the length till which we want to extract the string part.

Its parameters are the start and end position of the substring that we want to extract

This method can handle negative indexes.

This method cannot handle negative indexes.

RELATED ARTICLES

Most Popular

Recent Comments