substr()method extracts parts of a string.
- The method begins to extract at the specified string position and returns a new string of specified length.
substr()method does not change the original string. Instead, it returns a new string, containing the trimmed part of the text.
- An empty string is returned if length is 0 or negative.
- You may use a negative number to specify the trim start position counting from the end of a string.
Usage and Purpose Explained
substr() will not influence the original string. Instead, the functions generates a separate string to represent the part that was taken from the original one.
Theory is great, but we recommend digging deeper!
In the parentheses, you can notice the start parameter, indicating from which index should the function commence the extraction process. It is required to define. More details on this parameter can be found in the table below. The second parameter is optional and called length. It indicates how long should the new string be.
|start||Required. Specifies the position (in character index) where to start trimming.|
|If the parameter is greater than or equal to the length of the string, it will return an empty string.|
|If the parameter is negative, it will count characters from the end of the string.|
|If the parameter is larger than the string or negative, the start is set to 0.|
|length||Not required. Specified the length of the extracted string. If not set, it automatically extracts the rest of the original string.|
substr() and subString() functions. If you believe these functions to be exactly the same (a lot of beginners actually do), let us shed some light upon this matter.
substr() function can take two parameters that indicate the index to start the extraction, and the length of the new string to be created:
var str = "Example text"; var res = str.substr(0, 3);
substring() indicate the index to begin and conclude at - not the length.
There is no clear winner in this fight. Try both functions, and decide for yourself which one you're more comfortable using. It is, however, important you know and understand them both.
Code Examples: Chance to Practice
Click the Try it Live buttons to be transferred to a code editor. That's right: there's no need to leave the browser to practice! The examples below have the results displayed in the comment lines.
The first two code examples reveal how you can start the extraction process in indexes 3 and 8 and end it at the end of the string
var str = "Example text"; var res = str.substr(3);
var str = "Example text"; var res = str.substr(8);
The third example illustrates how the two last characters from the string are to be extracted:
var str = "Example text"; var res = str.substr(10,2);