🔥 Get 650+ Tech Books and Courses for $3/m for 3 months

Quick Tip: How to Split a String into Substrings in JavaScript

    Dianne Pena
    Share

    In this tutorial, you’ll learn the different ways you can split a string into substrings, and when each method is useful.

    Strings can be easily manipulated in JavaScript for different purposes — using native methods available in the language. We’ve recently covered how to convert a number to a string and how to convert a string to a number in JavaScript.

    Another way a string can be manipulated is by extracting parts of it to be used for something else. For example, you might have a full URL but want to extract just the hash part. Or you might have a list of items separated by commas and want to use each of these items separately.

    Split a String into Substrings Using substring()

    All strings in JavaScript have a substring() method. This method can be used to retrieve a substring at specific indices.

    substring() accepts two parameters. The first one is required, and indicates the index the substring starts at. The second is optional, and indicates the index the substring ends at. If the second parameter is omitted, the substring will start at the index provided as a first parameter and continue until the end of the string.

    It’s important to note that the first parameter is a 0-based index, meaning the first character is at index 0, the second is at index 1, and so on. Another important thing to note is that the second parameter is one greater than the index you want the substring to end at. For example, if you want the string to end at index 12, you provide 13 for the second parameter.

    For example:

    const a = 'Bytes and bits';
    const b = a.substring(10, 13);
    console.log(b); // "bit"
    console.log(a); // "Bytes and bits"
    

    In this example, substring() is used on the variable a to retrieve a substring. The substring starts at the index 10 and ends at the index 13. The returned value is bit. Notice that substring() returns the substring without mutating the value of the variable it’s used on.

    See the Pen
    Using substring to split string
    by SitePoint (@SitePoint)
    on CodePen.

    Retrieving Indices

    In most cases, you won’t know the start or end indices of the substring while writing the code. The index could be based on other inputs or variables.

    In those cases, you can use the indexOf() method. This method returns the index of a substring in a string if it occurs in it. If the substring doesn’t exist in the string, it returns -1.

    Once you retrieve the index using indexOf(), you can retrieve the substring.

    For example:

    const url = 'https://sitepoint.com#chapter_1';
    const hash = url.indexOf('#');
    if (hash !== -1) {
      console.log(url.substring(hash)); // "#chapter_1"
    }
    

    In this example, you retrieve the index of the hash character # in the variable url. If the value of the index is not -1, you retrieve the substring from url starting at the index of the hash.

    You can try it out in the following CodePen demo.

    See the Pen
    Using substring with indexOf to split string
    by SitePoint (@SitePoint)
    on CodePen.

    Split a String into Substrings Using split()

    Another useful way to retrieve a substring from a string is the split() method. If your string is a list of items separated by a delimiter, you can use the split() method to split the string into an array of substrings based on the delimiter.

    split() accepts two optional parameters. The first parameter is the delimiter that should be used to determine how the string is split. If none is provided, an array is returned with one item which is the string as a whole.

    The second parameter is a number that limits the number of substrings returned in the array. If provided, the string is split on the delimiter until the limit is reached, and the rest of the text in the string will be omitted from the array.

    For example:

    const str = 'Toyota,Nissan,Mercedes,Tesla';
    const cars = str.split(',');
    console.log(cars); // ["Toyota", "Nissan", "Mercedes", "Tesla"]
    

    In this example, split() is used on a string that contains a list of car brand names separated by the , delimiter. The returned array contains each car brand name as an item in the array.

    Note that split() returns the array of substrings without affecting the value of the string it’s used on.

    The following live example demonstrates how a string separated by commas can be split into list items.

    See the Pen
    Using split to get substrings
    by SitePoint (@SitePoint)
    on CodePen.

    Conclusion

    In this tutorial, you’ve learned how to split a string into substrings using the methods substring() and split().

    substring() is useful when you want to retrieve a single substring from a string at a specific index. You can use it with indexOf() to retrieve the starting or ending index of the substring.

    split(), on the other hand, is useful when you have a string that contains a list of items separated by a delimiter, such as a comma. You can then split the string into an array of substrings using split().

    If you found this article useful, you may also enjoy the following: