How word character is interpreted in character class?

后端 未结 2 749
感动是毒
感动是毒 2021-01-15 05:11

\\w - stands for [A-Za-z0-9_] Character class

But i am not able to understand how it is interpreted inside character class.

So when

2条回答
  •  生来不讨喜
    2021-01-15 05:48

    I believe that the main difference between both your examples is the location of your - character. What's happening here is that in this example:

    let test = (str) => /^[A-Za-z0-9_-~]+$/.test(str)
    
    console.log(test("T|"))
    

    It's evaluated as a range, like so:

    let test = (str) => /^[_-~]+$/.test(str)
    
    console.log(test("|"))
    

    will return true.

    Where in this one:

    let test = (str) => /^[\w-~]+$/.test(str)
    
    console.log(test("T|"))
    
    

    Since \w is a set of characters in and of itself, it's evaluating the character - by itself.

    The position of - and it's surrounding can make a huge difference in how it's interpreted.

    You could avoid that situation, altogether, by moving it to the end, like so:

    let test = (str) => /^[A-Za-z0-9_~-]+$/.test(str)
    
    console.log(test("T|"))
    

    which will return false

提交回复
热议问题