JS的test()方法

解析

解釋:js的test()方法用於檢測一個字符串是否匹配某個格式。
語法:RegExpObject.test(string)
返回值:如果String中含有RegExpObject中匹配的字符返回true,否則返回false

例子

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>test</title>
</head>

<body>

</body>
<script>
    /**
        解釋:js的test()方法用於檢測一個字符串是否匹配某個格式。
        語法:RegExpObject.test(string)
        返回值:如果String中含有RegExpObject中匹配的字符返回true,否則返回false
    
    */
    console.log(/123/.test('1234567')); // true
    console.log(/123/.test('2345678')); // false


    /**
        正則小知識:
        ^:起始位置
        $:結束位置
        \b:單詞邊界
    */
    console.log(/^HO/.test('HO1011')); // true
    console.log(/^MU/.test('H01002')); // false
    console.log(/^0MU/.test('MU1002')); // false

    console.log(/com$/.test('https:www.baidu.com')); // true
    console.log(/com$/.test('https:www.baidu.com/')); // false
    console.log(/com$/.test('https:www.baidu.com/s')); // false

    console.log(/\bis\b/.test('this is a pen')); // true
    console.log(/\bis\b/.test('this')); // false

    // 參考網址:https://blog.csdn.net/qq_41261490/article/details/82966077
</script>

</html>

後續未完,請繼續關注,Thanks!☺

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章