JavaScript SubString(): The Best Way To Extract Substring

Have you ever needed to extract a smaller portion of a string in JavaScript? This is where the JavaScript substring() method comes in handy. The substring() method allows you to extract a portion of a string and work with it.

In this blog post, we’ll explore:

  • What is substring()?
  • How to use substring() in JavaScript
  • JavaScript substring() vs slice()
  • Exploring JavaScript substring() methods
  • JavaScript substring() vs substr() methods
  • Common mistakes to avoid
  • Best practices to be followed.
Let’s dive in.

JavaScript extract substring using substring() method

The JavaScript substring() method is a built-in string function that allows you to extract a portion of a JavaScript string based on specified indices. It returns the extracted substring as a new string without modifying the original string.

The syntax for the substring methods is as follows:

string.substring(startIndex, endIndex)
ParameterDescription
startIndexRequired. Specifies the index at which the extraction should begin (inclusive).
endIndexOptional. Specifies the index at which the extraction should end (exclusive)

Here are a few important things to note about the substring() function:

  1. If the endIndex is not provided, the substring will include all characters from the startIndex to the end of the string.
  2. The substring method does not modify the original string. It creates and returns a new string containing the extracted portion.
  3. The substring indices are zero-based. Meaning the first character has an index of 0. The second character has an index of 1, and so on.
  4. If the startIndex is greater than the endIndex, the substring() method will automatically swap the values. This behavior ensures that the extracted substring is always in the correct order.

How to use JavaScript substring() to extract substring?

Here’s an example that demonstrates the usage of the substring() method to extract a substring from a string:

const greet = "Hello, World!";
const substring = greet.substring(0, 5);
console.log(substring); 
// Output: "Hello"
JavaScript substring() Method
JavaScript substring() Method

In this example, the substring() method is called on the greet string with a start index of 0 and endIndex 5. It extracts the characters from index 0 to 5 (exclusive) and returns the new string "Hello".

Here are two more examples, extracting a domain from a URL and JavaScript reverse string using the substring() method.

// Extracting a domain name from a URL
let url = "https://www.rajamsr.com/javascript-string-substring/";
let startIndex = url.indexOf("//") + 2;
let endIndex = url.indexOf("/", startIndex);
let domain = url.substring(startIndex, endIndex);
console.log(domain);
// Output: "www.rajamsr.com"

// Reversing a string
let originalString = "racecar";
let reversed = "";
for (let index = originalString.length - 1; index >= 0; index--) {
  reversed += originalString.substring(index, index + 1);
}

console.log(reversed); 
// Output: "racecar"

JavaScript substring() vs slice()

In JavaScript, to extract a substring from a string, you might come across two similar methods: substring() and slice(). While they may appear similar, there are subtle differences between them.

The main difference lies in how they handle the parameters. The substring() method takes two arguments, whereas the JavaScript slice() takes the starting and optional ending indexes. This distinction impacts the return values and behavior of the methods.

For example, consider the following code snippet:

const greet = "Hello, World!";

console.log(greet.substring(0, 5)); 
// Output: "Hello"

console.log(greet.slice(0, 5));     
// Output: "Hello"

In this case, both substring and slice will return the same result, as the ending index is exclusive. However, when dealing with negative indices or omitted parameters, the behavior of substring and slice diverges

Exploring JavaScript substring() methods

Now that we understand the basic differences, let’s explore some common scenarios and techniques involving substrings.

1. JavaScript extract substring before a character

Conversely, you may want to extract the portion of the string that appears before a certain character. We can achieve this using the JavaScript indexOf() and substring() methods:

const greet = "Hello, World!";
const delimiter = ",";
const substringBefore = greet.substring(0, greet.indexOf(delimiter));
console.log(substringBefore); 
// Output: "Hello"

2. Substring after a character

Often, you’ll need to extract a substring that comes after a specific character. To accomplish this, we can combine the same indexOf() and substring() methods:

const greet = "Hello, World!";
const delimiter = ",";
const substringAfter = greet.substring(greet.indexOf(delimiter) + 1);
console.log(substringAfter); 
// Output: " World!"

3. Substring() using negative index

If the JavaScript substring() method’s starting index is negative, it is treated as 0. Let’s see an example:

const greet = "Hello, World!";
console.log(greet.substring(-5)); 
// Output: "Hello, World!"

In the above code example, the negative number -5 is converted to 0, and substring() returns the substring starting from index 0. 

If you want to extract part of the string from the end, refer to the below method.

4. Extract part of string using substring() from the end

If you find yourself needing to extract substrings from the end of a string, you can use the negative index approach. Here’s an example of getting part of a string from the end:

const greet = "Hello, World!";
console.log(greet.substring(greet.length - 6)); 
// Output: "World!"

5. Substring() using regular expressions

Regular expressions (regex) offer powerful pattern-matching capabilities. JavaScript string substring() method can be combined with regex for more advanced substring extraction. Let’s take a look:

const greet = "Hello, World!";
const regex = /Wo[a-z]+/;
const substringWithRegex = greet.substring(greet.search(regex));
console.log(substringWithRegex); 
// Output: "World"

6. Removing the last character with substring

Occasionally, you might need to remove the last character from a string using a substring. Although there isn’t a direct substring() method for this purpose, we can achieve it with a slight workaround:

const greet = "Hello, World!";
const substringWithoutLastChar = greet.substring(0, greet.length - 1);
console.log(substringWithoutLastChar); 
// Output: "Hello, World"

In the above code, we are extracting from index 0. JavaScript string length property returns the number of characters in a string. If we subtract -1 from the length, it will return the substring starting from index 0, excluding the last character.

Differences between JavaScript substring() vs substr() vs slice() methods

The JavaScript substring() , substr() and slice() methods are used to extract substrings from a string. However, they have some key differences. Here are the main distinctions between the three methods:

Differences between JavaScript substring() vs substr() vs slice() methods
Differences between JavaScript substring() vs substr() vs slice() methods

JavaScript substr() deprecated

It’s worth noting that the method substr() is deprecated.If you are already using substr() in your application code, replace all instances with the substring() method.

Common mistakes when using substring

Now that we know how to use substring(), let’s look at some common mistakes to avoid.

Index out of range errors

One common mistake is to use an index that’s out of range. This can cause an error. To avoid this, we can check the length of the string before using a substring.
const greet = "Hello World";

if (greet.length > 5) {
  const sub = greet.substring(0, 5);
  console.log(sub); 
} else {
  console.log("String is too short!");
}
// Output: "Hello"

Best practices when using substring() method

Here are some best practices to keep in mind when using substrings.

  • Checking the length of the string:  Before using a substring, it’s a good idea to check the length of the string to avoid index out-of-range errors.
  • Using variables to store the start and end parameters: If you plan on using the start and end parameters more than once, it’s a good idea to store them in variables to avoid duplicating code.
  • Using a function to create a substring: If you need to extract a substring multiple times, it’s a good idea to create a function to do this. This will make your code more readable and maintainable.

Conclusion

In this blog post, we’ve explored the syntax of the method, how to use it in the JavaScript substring() method, common mistakes to avoid, and best practices. With this knowledge, you should be able to use substring to extract and work with smaller portions of strings in your JavaScript code.

Remember to always double-check the values of the start and end parameters to avoid common mistakes, and use best practices like checking the length of the string and creating functions when necessary.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top