In JavaScript, substring extraction is mainly through one of the three methods: Slice, Substring, and Substr.
// substring
// Syntax: string.substring(indexA [, indexB])
"Good news, everyone!".substring(5,9);
// 'news'
// substr
// Syntax: string.substr(start [, length])
"Good news, everyone!".substr(5,4);
// 'news'
But they differ in some important ways:
1. The substr() method extracts the specified number of characters from the specified position.
param: start is the position index to start extracting characters, length is the number and length of extracted characters.
return: a new string. length characters starting at start.
There is inconsistent performance in different browsers. Modern browsers allow the start index parameter to be a negative number to indicate the number of characters to be extracted starting from the end of the string. However, in browsers of IE8 and below, the minimum start index parameter is calculated from 0. [ substr is an additional ECMAScript feature for web browsers. It is not recommended to use it when the start index is a negative value]
console.log("(1): " str.substr(1)); // (1): bcdefghij
console.log("(1,2): " str.substr(1,2 )); // (1,2): bc
console.log("(-3): " str.substr(-3)); // (-3): hij
console.log("(-3,2): " str.substr (-3,2)); // (-3,2): hi
console.log("(20, 2): " str.substr(20,2)); // (20, 2):
console.log("(-20, 2): " str .substr(-20,2)); // (-20, 2): ab
// ie8 and below
console.log("(-3): " str.substr(-2)); // (-20, 2): hij
console.log("( -3, 2): " str.substr(-2)); // (-20, 2): ab
// Displays "Moz"
console.log(anyString.substring(0,3));
console.log(anyString.substring(3,0));
// Displays "lla"
console.log(anyString.substring(4,7));
console.log(anyString.substring(7,4));
// Displays "Mozill"
console.log(anyString.substring(0,6));
// Displays "Mozilla"
console.log(anyString.substring(0,7));
console.log(anyString.substring(0,10));
3.slice extracts a part of the string.
param: The position index at which beginSlice starts to extract characters, which can be negative. If it is a negative value, it is regarded as (sourceLength-beginSlice). sourceLength is the length of the string, that is: the position endSlice starting from the end of the string. The position index of the character at which the extraction ends. If omitted, extraction is completed. If negative, it is treated as (sourceLength-endSlice).
return: Returns a new string, starting with start (including start) and ending with end (excluding end).
All parameters can be negative. If the index is negative, it will be counted from the end of the string.
var str = "The morning is upon us.";
str.slice(-3); // "us."
str.slice(-3, -1); // "us "
str.slice(0, -1); // "The morning is upon us"