Can Javascript RegExp do partial case insensitivity?

后端 未结 5 604
我寻月下人不归
我寻月下人不归 2021-01-14 14:35

I want to know if Javascript RegExp has the ability to turn on and off case insensitivity within the regular expression itself. I know you can set the modifier for the entir

5条回答
  •  花落未央
    2021-01-14 14:54

    You can write the RegExp in case-sensitive "longhand"

    /[tT][eE][xX][tT] [tT][oO] [sS][eE][aA][rR][cC][hH] TOP SECRET/
        .test('text to search TOP SECRET');
    // true
    

    An alternative approach is two regular expressions, an insensitive one followed by a strict one

    function test(str) {
        var m = str.match(/text to search (TOP SECRET)/i);
        return (m || false) && /TOP SECRET$/.test(m[1]);
    }
    
    test('text to search TOP SECRET'); // true
    test('text to search ToP SECRET'); // false
    

    Further, function test above can be optimised in this specific case (as the TOP SECRET part is effectively a string literal which will always have exactly the same form), it doesn't require a second full RegExp test to check it, i.e. you can do

    (m || false) && 'TOP SECRET' === m[1];
    

提交回复
热议问题