主要区别在于
substr()允许您指定要返回的最大长度
substring()允许您指定索引,第二个参数不包含在内
substr()和substring()之间还有一些其他细微之处,例如对相等参数和负参数的处理。还要注意substring()和slice()相似,但并不总是相同。
//*** length vs indices:
"string".substring(2,4); // "ri" (start, end) indices / second value is NOT inclusive
"string".substr(2,4); // "ring" (start, length) length is the maximum length to return
"string".slice(2,4); // "ri" (start, end) indices / second value is NOT inclusive
//*** watch out for substring swap:
"string".substring(3,2); // "r" (swaps the larger and the smaller number)
"string".substr(3,2); // "in"
"string".slice(3,2); // "" (just returns "")
//*** negative second argument:
"string".substring(2,-4); // "st" (converts negative numbers to 0, then swaps first and second position)
"string".substr(2,-4); // ""
"string".slice(2,-4); // ""
//*** negative first argument:
"string".substring(-3); // "string"
"string".substr(-3); // "ing" (read from end of string)
"string".slice(-3); // "ing"
substring
在Chrome上的表现优于其他所有工具。