JavaScript substring

The JavaScript substring() function is one of the string methods used to pick a part (portion) of a string and return a new string. The substring function will accept two integer values. The first integer value is the index position where the extraction starts, and the second integer value is where the removal ends.

JavaScript substring syntax

The syntax of the substring() function to extract a portion from the original string is shown below.

String_Object.substring(Start, End)

From the above syntax, the substring() function accepts two parameter values. On which, the second parameter is optional.

  • String_Object: It is a valid string from which you want to extract a portion.
  • Start: Index position from where you want the extraction process to begin.
  • End: Please specify the index position where the extraction stops. It is an optional parameter, and if you ignore it, the JavaScript substring() function starts from the first index position and continues to the end of the string.

Return Value: The substring() function does not modify the original string. It returns a new string that contains a portion extracted (between start and end indices) from the original.

How JavaScript substring() function work?

The substring() starts extracting from the start index position, but it does not include the character at the last index position. For instance, (0, 5) means (0, 4), and it returns the first four characters.

  • If the end (second) parameter is undefined or omitted, the substring() function extracts characters from the start (first parameter) to the end of the string.
  • If we pass the same value to both parameters, the JavaScript substring() returns an empty string.
  • If we pass negative indices, the substring() function converts them to 0.
  • If the start index position (1st argument) > end index position (2nd argument), the substring() function automatically swaps their positions. For instance, (10, 4) automatically becomes (4, 10).

JavaScript substring function examples

This section shows how to use the substring() function to extract the first N characters, last N characters, or the middle portion of a string. Before going into the example, you must practically understand the return value.

As we mentioned earlier, the substring() function does not modify the original string. Instead, it returns a new string with the extracted characters between the two index positions.

let s = 'New Delhi';
let n = s.substring(4);
console.log(s);
console.log(n);
New Delhi
Delhi

To alter the original, we must reassign the result ot the same variable.

let s = 'New Delhi';
s =  s.substring(4);
console.log(s);
Delhi

JavaScript substring before characters

When we use the first argument (starting index) value as 0, the JavaScript substring() function starts extracting the text from the beginning of a string.

In the example, we use zero and 11 as the starting and ending index positions of the substring() function. So, it starts extracting the string from the first character and goes up to the 10th index position.

let s = 'Happy Christmas';
console.log(s.substring(0, 11));
Happy Chris

NOTE: Please change the second argument value to understand the behaviour. Remember, the substring() function does not move to the 11th position. It stops at the 10th index position.

JavaScript substring with the starting Index value

If we pass a single integer value as the substring() function argument, it is considered the first parameter (starting index position). In the example below, we pass 4 as the starting index position.

The substring() function starts extracting characters from the 4th position and moves to the end of the string. The default value of the second argument (end position) is the total number of characters in a string.

let s = 'New Delhi';
console.log(s.substring(4));
Delhi

JavaScript substring last N characters

Similar to the above example, we can use a single argument of the JavaScript substring() function to extract the last N characters from a given string. For this, we must use the length property to get the total number of characters in a string.

Here, the total length is 15 characters, and 15 -9 is 6. The substring() function considers 6 as the starting index position and extracts characters till the end of the string. The character at the 6th index position is C.

let s = 'Happy Christmas';
console.log(s.substring(s.length - 9));
Christmas

JavaScript substring after character

The above mentioned examples extract a portion of an original string. However, we are using the substring() function to extract a portion from the beginning of a string or going to end.

The following example illustrates the usage of the substring() function to extract a portion from the middle of a string. If we use a starting index position other than 0, and an ending index position other than the maximum length or empty, we can extract a portion from the middle.

Here, the extraction starts at the 3rd index position (p) and ends at the 11th index position (t).

let s = 'Happy Christmas';
console.log(s.substring(3, 12));
py Christ

JavaScript find substring in a string Example

The following example helps understanding substring() function and how it returns a portion of a string. Remember, if the second index value is higher than the first index, it will swap the two arguments. And, if you are using negative numbers as an argument, it will consider zero.

The second line of JavaScript code extracts the original string, starting at index position 2 and ending at 12. Next, we ignored the second argument, which means it will start at index position 2 and end at the last.

Next, we specified the first index as 13 and the second as 2. This JavaScript substring() function swaps two arguments, which means that it is equal to Str1.substring(2, 13).

<!DOCTYPE html>
<html>
<head>
    <title> SubStringJavaScript </title>
</head>
<body>
    <h1> JavaScriptSubString </h1>
<script>
    var Str1 = "Tutorial Gateway";
    var Str2 = Str1.substring(2, 13);
    var Str3 = Str1.substring(0, 13);
    var Str4 = Str1.substring(2);
    var Str5 = Str1.substring(13, 2);
 
    document.write(Str2 + "<br \>");
    document.write(Str3 + "<br \>");
    document.write(Str4 + "<br \>");
    document.write(Str5);

</script>
</body>
</html>
JavaScript substring function Example

Extract the first character from a string

To understand it simply, we used the JavaScript substring() function to extract the first character from a given string. Here, it starts at the first index position and ends at the same position.

let s = 'Washington';
console.log(s.substring(0, 1));
W

We can also use the index position to extract the first character from a string. Here, s[0] is the first character and s[n] is the nth character.

let s = 'Washington';
console.log(s[0]);

Get the first word from a string

Similar to the above example, we can use the JavaScript substring() function to extract the first word from a string. The indexOf() method in the example below finds the position of the first whitespace (word separator), and the substring() returns the character starting from position 0 to that position.

let s = 'New York City';
let f = s.substring(0, s.indexOf(" "))
console.log(f);
New

How to find an empty String?

The JavaScript substring() function in the if else statement checks whether the given string is empty or not. If true, print the empty message. Otherwise, display the text.

let s = '';
if(s.substring(0,1) === '')
{
  console.log('String is Empty');
}
else {
  console.log(s);
}
String is Empty

If you change the s value to a random text, the above code returns a text instead of the empty string message.

JavaScript substring handling Negative Indices

Unlike other functions, the substring() function does not treat the negative values as starting from the right side. The substring() function converts or treats negative values as zeros.

Negative Index as the starting Index

In the following example, we used the negative index value (-2) as the starting index position. However, the JavaScript substring() function treats (-2, 7) as (0, 7) and returns the text starting at 0 to 6.

let s = 'New Jersey';
let res = s.substring(-2, 7);
console.log(res);
New Jer

Negative Value as end Index

In the example below, we used the JavaScript substring() function with negative indices as the end index position. However, the substring() method treats (3, -5) as (3) and returns the first three characters as the output.

let s = 'New Jersey';
let res = s.substring(3, -5);
console.log(res);
New

JavaScript substring with Negative Start and End Indices

When we use negative indices as starting and ending index positions (both arguments), the substring() function returns an empty.

In the example below, the substring() function converts or treats (-1, -4) as (0) and returns nothing as the output. 

let s = 'Washington';
let res = s.substring(-1, -4);
console.log(res);

Using only one Negative Index number

If you pass only one argument and it is a negative number, the JavaScript substring() function returns the original string as the output.

In the example below, the substring() function considers (-3) as (0) and returns the complete string as the output. 

let s = 'Washington;
let res = s.substring(-3);
console.log(res);
Washington

JavaScript substring swaps indices

The substring() function has a beautiful concept called automatic swapping of the two parameter values. If the first argument (starting index position) is greater than the second argument (ending index position), the substring() function automatically swaps their positions. It means the first argument becomes the second, and the second parameter becomes the first.

To demonstrate it, we used the substring with a starting index value of 17 and an end value of 4. Here, startIndex > endIndex, so the JavaScript substring() function swaps their positions. It means (17, 4) becomes (4, 17). The program below returns the string characters starting at index position 4 and finishing at 16.

let s = 'The United States Of America';
let res = s.substring(17, 4);
console.log(res);
United States

Let me provide another example of the swap technique. Here, we used 3 as the starting index position and 0 as the end index value. It means the substring() function treats (3, 0) as (0, 3) and returns New as the output.

let s = 'New York';
let res = s.substring(3, 0);
console.log(res);
New

JavaScript substring function real-time examples

The following are some of the substring function examples at the production level. You can use them to understand the substring() usage in real-time.

Extract Domain Name from Email

In the following example, the indexOf function finds the index position of the symbol. Next, the substring function returns the text after that (@) symbol. Here, the indexOf returns the exact position; we must add 1 to start extracting text after the @ symbol.

let mail = 'contact@tutorialgateway.org';
const domain = mail.substring(mail.indexOf('@') + 1);
console.log(domain);
tutorialgateway.org

JavaScript substring indexOf

Similar to the above JavaScript substring example, we can extract the username from a given email address. To do so, we must use 0 as the starting position and the @ symbol position as the end position.

The following example returns a substring starting from the first character to the character before the @ symbol.

let mail = 'contact@tutorialgateway.org';
const domain = mail.substring(0, mail.indexOf('@'));
console.log(domain);
contact

Extract the last four digits of a Credit Card

Imagine our credit card number is stored in a string format, and the task is to retrieve the last four digits.

let number = '1234567893456789';
const lastfour = number.substring(number.length - 4);
console.log(lastfour);
6789

Masking the Credit Card Number

The above example extracts and displays the last four digits of a user’s 16-digit credit card number. However, the following JavaScript substring function example masks the first 12 digits in a credit card and displays the last four digits.

Here,

  • number.substring(number.length – 4) returns the last four digits.
  • ‘****-****-****-‘ + last means insert those star symbols and add the last four digits.
function maskcard(number) {
  const last = number.substring(number.length - 4);
  return '****-****-****-' + last;
}
let n = '1234-5678-9345-7787';
console.log(maskcard(n));
****-****-****-7787

JavaScript substring for Email Masking

In the example below,

  • email[0] means the first character in a given email ID. We take the third ID for the explanation. So, the first character is c.
  • email.indexOf(‘@’) returns the position of the @ symbol. Here, the @ symbol is at the 3rd position.  So, i = 3.
  • *’.repeat(i – 2) repats printing * symbol for one time because i = 2 returns 1.
  • email.substring(i – 1) returns the substring starting from the character before the @ symbol. It means t@example.com.
  • email[0] + ‘*’.repeat(i – 2) + email.substring(i – 1) = c + * + t@example.com. It means c*t@example.com.
function maskMail(email) {
  const i = email.indexOf('@');
  return email[0] + '*'.repeat(i - 2) + email.substring(i - 1);
}
console.log(maskMail('davidmiller@adventureworks.com'));
console.log(maskMail('contact@tutroialgateway.org'));
console.log(maskMail('cat@example.com'));
d*********r@adventureworks.com
c*****t@tutroialgateway.org
c*t@example.com

Mask OTP

The JavaScript substring function in the following example extracts the first two digits in a given OTP number. The assignment operator adds four asterisk symbols to it.

TIP: If your OTP is a four-digit number, delete the extra two stars in the function and remove two digits in a console.log().

function maskOTP(otp) {
  return otp.substring(0, 2) + '****';
}
console.log(maskOTP('234567'));
23*****

JavaScript substring from end: Get the file extension

A file name can be anything based on the operating system. However, each file name has an extension (csv, txt, doc, pdf, png, etc), and our task is to extract the file extension.

In the example below, the lastIndexOf() function retrieves the last position of the (.) symbol. The substr () function returns the text (characters) after that symbol.

function getExtension(name) {
  return name.substring(name.lastIndexOf('.') + 1);
}
let filename = 'Sample.doc';
console.log(getExtension(filename));
doc

Trim the string before extracting

Before starting to extract a part of an original string, it is safe to use the trim() function to remove the trailing and leading whitespaces.

The first example returns the substring with two extra blank spaces at the beginning, and it considers them while extracting the substring. The next statement has the cleaned text, so it returns the correct word.

let text = '  New Jersey  ';
console.log(text.substring(0, 3));

let formatted = text.trim();
console.log(formatted.substring(0, 3));
  N
New

JavaScript substring function for URL Extraction

The example below uses the indexOf(), lastIndexOf(), and substring() functions to extract the website name, path, and slug information.

  • url.indexOf(‘://’) + 3: Those characters found at the 5th position and we added three to them. The character at the 8th position is the starting point of the website name.
  • url.indexOf(‘/’, httpsInfo): Finds the index position of the / symbol starting from the 8th position.
  • url.substring(httpsInfo, actualPath): Extract the text stating from the 8th position to the 19th position (-1) (where / symbol found).
  • url.substring(url.lastIndexOf(‘/’) + 1): Extract the text starting from the last index position of the / symbol to the string ending.
const url = 'https://example.com/news/apple-release';

const httpsInfo = url.indexOf('://') + 3;
const actualPath = url.indexOf('/', httpsInfo);

let domain, path, slug;
if (actualPath === -1)
{
  domain = url.substring(httpsInfo);
  path = '/';
  slug = '/';
}
else
{
  domain = url.substring(httpsInfo, actualPath);
  path = url.substring(actualPath);
  slug = url.substring(url.lastIndexOf('/') + 1);
}
console.log(domain);
console.log(path);
console.log(slug);
example.com
/news/apple-release
apple-release

Generate a Text Preview for CMS

If you observe any CMS or website, it provides a preview of an article with a 50 or 100-character limit. Once the limit is exceeded, it simply shows … and adds a read more link.

The following JavaScript substring() function example checks the string length and, if it is less than the given limit, shows the complete text. Otherwise, display only 25 headers followed by …

function textPreview(text, limit)
{
  if (text.length <= limit)
  {
    return text;
  }
  return text.substring(0, limit) + '...';
}

console.log(
  textPreview(
    'It is a sample document explaining something about ' +
    'the WordPress or other CMS systems. ',
    20),);
It is a sample docum...

Shorten URL Logic

In some social sharing platforms, they won’t use the actual URL coming from the original post. Instead, they create a shorter URL slug and redirect to the original link.

The following script accepts a URL from any domain and extracts the last portion (Actual slug) and appends it to its own shortened URL.

function getShortCode(url) {
  return 'https://abc.in/' + url.substring(url.lastIndexOf('/') + 1);
}
let url = 'https://www.example.com/blog/sample-post';
console.log(getShortCode(url));
https://abc.in/sample-post

FAQs

JavaScript substring vs slice

Both the substring() and slice() functions are identical in nature; they differ when we pass negative index values and when we use the first argument greater than the second (swapping techniques).

Positive Numbers: As you can see from the example below, both the substring() function and the slice() method return the same output for the positive numbers as arguments.

let s = 'New Delhi Capital';
console.log(s.substring(4, 9));
console.log(s.slice(4, 9));
Delhi
Delhi

substring and slice working with Negative Values

The following example returns New York as output because it converts the starting index value from minus four to zero

let s = 'New York';
let res = s.substring(-4);
console.log(res);
New York

If we use the same example and replace the JavaScript substring() function with the slice() function, the result becomes different. When we pass a negative value, the slice() function starts looking from the right side (end position) and moves towards the starting position. The code below extracts the last four characters in a string.

let s = 'New York';
let res = s.slice(-4);
console.log(res);
York

If we use negative numbers as the two arguments, the substring () returns an empty string. On the other hand, the slice() function returns a text looking from right to left.

let s = 'New York';
console.log(s.substring(-7, -1));
console.log(s.slice(-7, -1));
ew Yor

Index swapping: Unlike the JavaScript substring() function, the slice() function won’t support automatic index swapping.

This substring() function in the example below automatically swaps the starting and ending index positions to return the output. Here, (13, 4) is converted to (4, 13), and the substring starts extracting characters starting at the 4th index position and moves up to the 12th.

let s = 'New Delhi Capital';
console.log(s.substring(13, 4));
Delhi Cap

If we apply the same to the slice() function, it returns an empty string. The slice() function does not automatically swap two parameters; it does not understand what we are looking for.

let s = 'New Delhi Capital';
console.log(s.slice(13, 4));

When to use them

  • If there are no negative indices, use either the slice() or substring() function.
  • If you need the support of the negative indices to look from the string end position and move towards the start position, use the slice() method.
  • Use slice() to work with arrays.
  • In modern code, most developers opt for the slice() function.

JavaScript substring vs substr

At the time of writing, the substr() function is deprecated; consider avoiding its use in modern applications. Instead of the substr() method, we can choose between the substring() and slice() functions.

In both functions, the first parameter is the starting index position from where the string extraction starts. Unlike the substring() function, the second parameter value of the substr() is a length property.

In the example below, the JavaScript substring() function starts extracting the string from the 4th index position and stops at the 10th index position. On the other hand, the substr() function starts at the 4th position and extracts 11 characters from that position. The extracted string length must be 11 characters.

let s = 'New Year Celebration';
console.log(s.substring(4, 11));
console.log(s.substr(4, 11));
Year Ce

Year Celebr

When it comes to negative values, the substr() function starts looking from the string’s end position and moves towards the start. As we all know, the substring() treats negative indices as zeros.

In the example below, the substring() function converts (-16, 4) to (0, 4) and returns the first three characters from the original string.

The substr() starts the string extraction from the negative 16th index position, starting from the end point and moving towards the start. Here, n is at the negative 1st position, o at 2nd, and Y is at the 16th position. From that position, extract four characters from a given string.

let s = 'New Year Celebration';
console.log(s.substring(-16, 4));
console.log(s.substr(-16, 4));
New
Year