判断字符串第一个和最后一个字符
原创2022年5月8日
判断字符串第一个和最后一个字符
笔者最近在开源一个项目,叫做 yidash(易大师) ,一个基于 lodash 扩展的业务工具函数库。
在实现其中一个 验证有效数字 函数的时候,需要判断一下,字符串的最后一个数字是不是点号(.)。
觉得原来的写法不优雅,于是去查阅了 js mdn (火狐开发者平台),看到了如下 2 个函数。
String.prototype.startsWith()
startsWith() 方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true 或 false。
const str1 = "Saturday night plans";
console.log(str1.startsWith("Sat"));
// expected output: true
console.log(str1.startsWith("Sat", 3));
// expected output: false
String.prototype.endsWith()
endsWith()方法用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的,根据判断结果返回 true 或 false。
const str1 = "Cats are the best!";
console.log(str1.endsWith("best", 17));
// expected output: true
const str2 = "Is this a question";
console.log(str2.endsWith("?"));
// expected output: false