Skip to content
陈随易陈随易
我的博客
    • 判断字符串第一个和最后一个字符
      • String.prototype.startsWith()
        • String.prototype.endsWith()
        • 前端如何写出优雅的异步处理代码

        判断字符串第一个和最后一个字符

        陈随易原创2022年5月8日
        • 编程技巧
        • JavaScript
        小于 1 分钟

        此页内容
        • String.prototype.startsWith()
        • String.prototype.endsWith()

        # 判断字符串第一个和最后一个字符

        笔者最近在开源一个项目,叫做 yidash(易大师) ,一个基于 lodash 扩展的业务工具函数库。

        开源地址:https://github.com/chenbimo/yidashopen in new window

        在实现其中一个 验证有效数字 函数的时候,需要判断一下,字符串的最后一个数字是不是点号(.)。

        觉得原来的写法不优雅,于是去查阅了 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
        
        1
        2
        3
        4
        5
        6
        7

        # 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
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        上次编辑于: 2022/5/8 下午1:50:01
        贡献者: chensuiyi
        下一页
        前端如何写出优雅的异步处理代码
        何以解忧,唯有代码
        Copyright © 2022 陈随易

        该应用可以安装在你的 PC 或移动设备上。这将使该 Web 应用程序外观和行为与其他应用程序相同。它将在出现在应用程序列表中,并可以固定到主屏幕,开始菜单或任务栏。此 Web 应用程序还将能够与其他应用程序和你的操作系统安全地进行交互。

        详情