Regex to check whether string starts with, ignoring case differences

后端 未结 5 2061
野性不改
野性不改 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: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.

提交回复
热议问题