关于字符串截取函数应该使用哪个的拙见
JS中常用的字符串截取函数有三个。
-
slice
/** * Returns a section of a string. * @param start The index to the beginning of the specified portion of stringObj. * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. * If this value is not specified, the substring continues to the end of stringObj. */ slice(start?: number, end?: number): string;
-
substring
/** * Returns the substring at the specified location within a String object. * @param start The zero-based index number indicating the beginning of the substring. * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. * If end is omitted, the characters from start through the end of the original string are returned. */ substring(start: number, end?: number): string;
-
substr
/** * Gets a substring beginning at the specified location and having the specified length. * @deprecated A legacy feature for browser compatibility * @param from The starting position of the desired substring. The index of the first character in the string is zero. * @param length The number of characters to include in the returned substring. */ substr(from: number, length?: number): string
可以看到slice和substring比较类似,可以接受两个参数,这两个参数都是字符串的下标。
而substr则不太一样,它的第一个参数也是下标,而第二个参数是截取的长度。
在某些情况下,截取一定的长度看起来貌似更好理解,不幸的是,我们从注解中可以看出substr已经被废弃了。MDN也这样提示我们。
既然被废弃了,那么我们就尽量不要去使用它。
然后就是比较类似的slice和substring,我的建议是只是用slice,因为它支持负数的小标,截取起来更加方便,让熟悉python字符串截取的我们倍感亲切。
let test = "wuuconix"
test = test.slice(0, -1)
console.log(test)
而substring则不支持负数下标。
所以之后遇到字符串截取问题不假思索地使用slice吧!