Regex to check whether string starts with, ignoring case differences

后端 未结 5 2029
野性不改
野性不改 2020-12-29 03:23

I need to check whether a word starts with a particular substring ignoring the case differences. I have been doing this check using the following regex search pattern but th

相关标签:
5条回答
  • 2020-12-29 03:38

    In this page you can see that modifiers can be added as second parameter. In your case you're are looking for 'i' (Canse insensitive)

    //Syntax
    var patt=new RegExp(pattern,modifiers);
    
    //or more simply:
    
    var patt=/pattern/modifiers;
    
    0 讨论(0)
  • 2020-12-29 03:39

    You don't need a regular expression at all, just compare the strings:

    if (stringToCheck.substr(0, query.length).toUpperCase() == query.toUpperCase())
    

    Demo: http://jsfiddle.net/Guffa/AMD7V/

    This also handles cases where you would need to escape characters to make the RegExp solution work, for example if query="4*5?" which would always match everything otherwise.

    0 讨论(0)
  • 2020-12-29 03:44

    I think all the previous answers are correct. Here is another example similar to SERPRO's, but the difference is that there is no new constructor:

    Notice: i ignores the case and ^ means "starts with".

     var whateverString = "My test String";
     var pattern = /^my/i;
     var result = pattern.test(whateverString);
     if (result === true) {
         console.log(pattern, "pattern matched!");
     } else {
         console.log(pattern, "pattern did NOT match!");
     }
    

    Here is the jsfiddle (old version) if you would like to give it a try.

    0 讨论(0)
  • 2020-12-29 03:47

    For cases like these, JS Regex offers a feature called 'flag'. They offer an extra hand in making up Regular Expressions more efficient and widely applicable.

    Here, the flag that could be used is the 'i' flag, which ignores cases (upper and lower), and matches irrespective of them (cases).

    Literal Notation:

    let string = 'PowerRangers'
    let regex = /powerrangers/i
    let result = regex.test(string) // true
    

    Using the JS 'RegExp' constructor:

    let string = 'PowerRangers'
    let regex = new RegExp('powerrangers', 'i')
    let result = regex.test(string)
    
    0 讨论(0)
  • 2020-12-29 04:04

    Pass the i modifier as second argument:

    new RegExp('^' + query, 'i');
    

    Have a look at the documentation for more information.

    0 讨论(0)
提交回复
热议问题