JavaScript String substr() Method

The substr method in JavaScript extracts a specified portion of a string and outputs it as a new string. The length of the extracted portion is determined by the parameter passed to the method. Notably, this operation does not alter the original string in any way.

Syntax

The syntax for the substr method is as follows:

Example

string.substr(start, length)

Parameter

The start parameter indicates the position in the string where the extraction will begin.

The parameter "length" is not mandatory and indicates the quantity of characters to retrieve.

Return

Part of the string.

JavaScript String substr Method Examples

Let's explore a few basic illustrations showcasing the utilization of the substr function.

Example 1

Let's explore a basic demonstration of how to output a substring from a string.

Example

Example

<!DOCTYPE html>

<html>

<head>

  <title>String</title>

</head>

<body>

  <script>

    var str = "Example";  

    document.writeln(str.substr(0,4));  

  </script>

</body>

</html>

Output:

Explanation:

A string variable named str is established in the script, containing the value "Sample". The script employs the substr function to extract a substring starting from index 0 (the initial character), which spans 4 characters. Upon execution, the script will display "Tpoi" on the webpage utilizing the document.writeln method. The substr function is utilized to isolate a segment of the string according to the specified starting position and length.

Example 2

Let's explore another illustration demonstrating how to display a segment of a string.

Example

Example

<!DOCTYPE html>

<html>

<head>

  <title>String</title>

</head>

<body>

  <script>

    var str = "Example";  

    document.writeln(str.substr(5,5));  

  </script>

</body>

</html>

Output:

Explanation:

A string variable named str is created in the script and initialized with the value "Example". Following this, a substring is obtained from the 5th index of the string "tTech", which retrieves the character "t". By invoking the substr function with the specified index and character count (5), the script successfully extracts "tTech". This extracted substring is then output to the web page using document.writeln. The substr function requires two arguments: the starting index of the substring and the count of characters to be extracted.

Example 3

In this instance, we will solely furnish the initial index.

Example

Example

<!DOCTYPE html>

<html>

<head>

  <title>String</title>

</head>

<body>

  <script>

    var str = "Example";  

    document.writeln(str.substr(5));  

  </script>

</body>

</html>

Output:

Explanation:

A string variable named str is declared in JavaScript and assigned the value "Example". By employing the substr(5) function, a substring starting from the 5th index to the end of the string is extracted. JavaScript string indices begin at 0. Hence, the output displayed on the webpage will be "tTech". The substr function retrieves a substring from the specified index to the end of the string.

Example 4

In this instance, we will demonstrate calling the method without any parameters. When called without arguments, the method will return the entire string.

Example

Example

<!DOCTYPE html>

<html>

<head>

  <title>String</title>

</head>

<body>

  <script>

    var str = "Example";  

    document.writeln(str.substr());   

  </script>

</body>

</html>

Output:

Output

Example

Explanation:

The variable str in JavaScript holds the value "Example". When the substr method is invoked without arguments, it begins at the starting index of 0 and encompasses the complete string. Consequently, the entire string "Example" is retrieved and exhibited on the webpage through document.writeln. This demonstration illustrates that utilizing substr without arguments results in the display of the entire original string.

Example 5

In this instance, we will specify a negative number as the initial index. When a negative number is used, the method begins retrieving from the end of the string.

Example

Example

<!DOCTYPE html>

<html>

<head>

  <title>String</title>

</head>

<body>

  <script>

    var str = "Example";  

    document.writeln(str.substr(-5, 5));  

  </script>

</body>

</html>

Output:

Explanation:

Assigning the string "Example" to a variable named str, we can utilize the substr(-5, 5) method to extract a substring. When using a starting index of -5, it signifies the fifth character from the end of the string, counting backwards to the character 't' in "Tech". The second parameter, which is 5, specifies the number of characters to extract from that position. Consequently, the output, "tTech", is then displayed on the web page using the document.writeln method.

Uses of the String substr Method

The substr function is utilized to retrieve a specific segment of a string by specifying a starting point and a length. While it is not commonly recommended for contemporary JavaScript programming, it might still be encountered in legacy codebases.

1. Extracting a specific portion of the string

The substr function is used for extracting a portion of a string by specifying the starting position and the length of characters to be extracted from that position.

Example

Example

let str = "JavaScript";

let sub = str.substr(4, 6);

console.log(sub);

Output:

Output

Script

Explanation:

A string variable named str is set to "JavaScript". The substr(4, 6) method is invoked on this string, extracting a substring that begins at the 4th index and spans 6 characters. The extracted substring, "Script", is stored in a variable named sub and then displayed on the console using console.log(sub).

2. Extracting the end of a string using negative index

Initial values that are below zero are calculated by counting backwards from the string's length.

Example

Example

let str = "Example";

let sub = str.substr(-4);

console.log(sub);

Output:

Explanation:

The provided code initializes a string variable named str with the content "Example". By using the substr(-4) function, the code extracts the last four characters starting from the fourth character from the end of the string. The extracted substring is stored in the variable sub and displayed on the console using console.log(sub).

3. Processing data

It is employed in data parsing or processing to handle fixed-length string data, commonly found in files or legacy systems.

Example

Example

let record = "A1234JohnDoe";  

let id = record.substr(1, 4); 

let name = record.substr(5, 7); 

console.log(id);

console.log(name);

Output:

Output

1234

JohnDoe

Explanation:

The code snippet presented above establishes a string labeled as record with the content "A1234JohnDoe". It showcases the encoding of organized data within a string with a consistent format. By utilizing substr(1, 4), a segment of 4 characters commencing from the first index up to the fourth index is captured, resulting in the identification value of "1234". Subsequently, employing substr(5, 7), the subsequent 7 characters starting from the fifth index are extracted, revealing the name as "JohnDoe". Both the identifier and the name extracted are then displayed on the console.

Conclusion

Within JavaScript, the substr method is employed to retrieve a portion of a string by specifying a starting point and a character count. Despite its support in numerous browsers, this method has been deemed deprecated and is no longer considered an official ECMAScript standard.

The utilization of substr is not recommended anymore because of its outdated status. Many developers now prefer using slice or substring methods as more favorable and completely standardized alternatives that provide similar functionality to substr. By opting for these methods instead of substr, you can enhance the compatibility, readability, and maintainability of your code.

Frequently Asked Questions (FAQs):

  1. What is the purpose of the substr function in JavaScript?

The substr function allows you to extract a specific segment of a string by defining a starting index and the number of characters to extract from that point onward. This extracted segment is returned as a new string.

  1. Could you provide the syntax for utilizing the substr method?
  2. Example
    
    string.substr(start, length)
    

start: The index to start extraction.

Is it possible to input negative values into the substr function when specifying the length parameter for character extraction?

Certainly. When the start parameter is a negative value, it indicates counting from the string's end in reverse. Nonetheless, the length value must remain a non-negative integer.

Code:

Example

let str = "hello";

let sub = str.substr(-2);

console.log(sub);

What occurs when the length parameter is not provided?

The inclusion of the length parameter in the substr function is not mandatory. In cases where the length is not specified, substr will extract characters from the start index to the end of the provided string.

Code:

Example

let str = "JavaScript";

let sub = str.substr(4);

console.log(sub);

Output:

Output

Script
  1. Is substr deprecated?

The substr function has been deprecated and is no more included in the ECMAScript standard. Although various browser implementations still support this function, it is advised against utilizing it in present-day code.

  1. Is substr functionality maintained in contemporary browsers?

Indeed, despite being deprecated, substr is still supported by most modern browsers for the sake of backward compatibility. However, it is advisable to avoid using substr due to its deprecated status.

  1. Is there a possibility that substr will be eliminated from JavaScript in the upcoming versions?

While there are no assurances, deprecated functionalities may potentially face elimination from the programming language or cease to function in certain settings. Hence, it is advisable to opt for the slice or substring functions over the substr method.

  1. Is it recommended to utilize substr in live code deployments?

It is recommended to steer clear of utilizing substr in live code environments. While it may be functional at present, its reliability in future setups is uncertain. It is advisable to opt for contemporary alternatives such as slice or substring.

Input Required

This code uses input(). Please provide values below: