In JavaScript, both the substr() and substring() functions are used to obtain a specified part of a string, but there are subtle differences between them. The following article will introduce you to the substr() and substring() functions so that you can understand the differences between the substr() and substring() functions. I hope it will be helpful to you.
str.substr() function
str.substr() function can start from a given character Returns the specified number of characters at the specified index in the string.
Basic syntax:
str.substr(start, len)
Parameters:
● start: Specify the position from which to start extraction, this parameter cannot be omitted ;The index of the first character is 0. If the start argument is positive and greater than or equal to the length of str, this function returns the empty string; if the start argument is negative, this function uses it as the index into the end of the string; if the start argument is negative or greater than the length of string , then the start parameter is set to 0.
● len: Specifies the number of characters to be extracted, which can be omitted. If not passed then it will extract the entire string.
str.substring() function
#str.substring() function removes the values between two specified indices in a string Gets the characters and returns a new string.
Basic syntax:
str.substring(start, end)
Parameters:
● start: Specify the starting position of extraction, cannot be omitted . The index of the first character is 0.
● End: Specifies the end position of the extraction (up to, but not including, the characters at the end position), which can be omitted. If not used, it will extract the entire string.
The difference between substr() and substring()
Let’s take a look at substr() and substring( through examples )
Example 1:
var a = "hello world!美丽的世界!"; //使用substr()函数 var str1=a.substr(7); console.log(str1); //使用substring()函数 var str2=a.substring(7); console.log(str2);
Output:
Example 2:
var a = "hello world!美丽的世界!"; //使用substr()函数 var str1=a.substr(7,14); console.log(str1); //使用substring()函数 var str2=a.substring(7,14); console.log(str2);
Output:
Related video tutorial recommendation: "JavaScript Tutorial"
The above is the detailed content of What is the difference between substr() and substring() in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!