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

    Dianne Pena
    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:

    Frequently Asked Questions (FAQs) about JavaScript String Substrings

    What is the difference between the split() and substring() methods in JavaScript?

    The split() and substring() methods in JavaScript are both used to manipulate strings, but they serve different purposes. The split() method divides a string into an array of substrings based on a specified separator and returns the new array. On the other hand, the substring() method extracts characters from a string between two specified indices and returns the new substring. It does not alter the original string.

    Can I use the split() method with multiple separators in JavaScript?

    Yes, you can use the split() method with multiple separators in JavaScript. The separators are defined in a regular expression, allowing you to split a string at multiple different characters. For example, you could split a string at both spaces and commas.

    How can I reverse a string in JavaScript using the split() method?

    To reverse a string in JavaScript using the split() method, you would first split the string into an array of characters, reverse the array using the reverse() method, and then join the array back into a string using the join() method. Here’s an example:

    let str = "Hello World";
    let reversedStr = str.split("").reverse().join("");
    console.log(reversedStr); // Outputs: "dlroW olleH"

    How can I use the split() method to get the last element of a string in JavaScript?

    You can use the split() method in combination with the pop() method to get the last element of a string in JavaScript. First, split the string into an array of words. Then, use the pop() method to remove and return the last element of the array. Here’s an example:

    let str = "Hello World";
    let words = str.split(" ");
    let lastWord = words.pop();
    console.log(lastWord); // Outputs: "World"

    Can I use the split() method to split a string into characters in JavaScript?

    Yes, you can use the split() method to split a string into characters in JavaScript. To do this, you would pass an empty string as the separator to the split() method. Here’s an example:

    let str = "Hello";
    let characters = str.split("");
    console.log(characters); // Outputs: ["H", "e", "l", "l", "o"]

    How can I use the split() method to count the number of words in a string in JavaScript?

    You can use the split() method to count the number of words in a string in JavaScript. First, split the string into an array of words. Then, use the length property of the array to get the number of words. Here’s an example:

    let str = "Hello World";
    let words = str.split(" ");
    let wordCount = words.length;
    console.log(wordCount); // Outputs: 2

    Can I use the split() method with a limit in JavaScript?

    Yes, you can use the split() method with a limit in JavaScript. The limit is a second optional parameter that you can pass to the split() method. It specifies the maximum number of splits to be made. Here’s an example:

    let str = "Hello World";
    let words = str.split(" ", 1);
    console.log(words); // Outputs: ["Hello"]

    How can I use the split() method to split a string at line breaks in JavaScript?

    You can use the split() method to split a string at line breaks in JavaScript. To do this, you would pass a regular expression that matches line breaks as the separator to the split() method. Here’s an example:

    let str = "Hello\nWorld";
    let lines = str.split(/\n/);
    console.log(lines); // Outputs: ["Hello", "World"]

    Can I use the split() method to split a string into sentences in JavaScript?

    Yes, you can use the split() method to split a string into sentences in JavaScript. To do this, you would pass a regular expression that matches sentence-ending punctuation as the separator to the split() method. Here’s an example:

    let str = "Hello. World!";
    let sentences = str.split(/[.!?]/);
    console.log(sentences); // Outputs: ["Hello", " World", ""]

    How can I use the split() method to split a string at commas and spaces in JavaScript?

    You can use the split() method to split a string at commas and spaces in JavaScript. To do this, you would pass a regular expression that matches both commas and spaces as the separator to the split() method. Here’s an example:

    let str = "Hello, World";
    let words = str.split(/[, ]/);
    console.log(words); // Outputs: ["Hello", "", "World"]