Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Javascript RegExp do partial case insensitivity?

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 entire regex expression, but that isn't what I'm talking about.

For example, my search string could be:
teXT To seArcH TOP SECRET.

I want to find the insensitive case part "text to search" and then force case sensitivity for "TOP SECRET".

Thus, this wouldn't match (because of case sensitivity for top secret):
teXT To seArcH Top Secret

but this would match (first section case doesn't matter):
text to search TOP SECRET

In Perl, you can do this within the search string. Does Javascript's regular expression engine support anything like this?

like image 444
Stephen Schrauger Avatar asked Sep 24 '26 11:09

Stephen Schrauger


1 Answers

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];
like image 165
Paul S. Avatar answered Sep 27 '26 00:09

Paul S.