How do I get a substring from a string in JavaScript?

To get a substring from a string in JavaScript, you can use the built-in string.substring(start, end) method. The first parameter specifies the index of the first character to include in the returned substring (indexing starts from zero). The second parameter is optional and specifies the index of the first character to exclude from the returned substring (the character at the specified index is not included in the substring). If the second parameter is not specified, then the substring() method copies all characters up to the end of the string. If the "start" parameter is equal to the "end" parameter, then the substring() method will return an empty string. If the "start" parameter is greater than the "end" parameter, then the method will swap its values. If a negative number, undefined, NaN is specified as indexes values, then this value is considered equal to zero. If one of the parameters is greater than or equal to the length of the string, then the value is considered equal to the length of the string. The substring() function does not change the original string but returns a new string containing the specified part of the given string. Click Execute to run the JavaScript Substring Example online and see the result.
Loading...