Regex to check whether string starts with, ignoring case differences

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

提交回复
热议问题