skip to Main Content

What’s the difference between /^(?=.*[w])$/ and /^(?=.*[w]).

  • /^(?=.*[w])$/.test('a') return false
  • /^(?=.*[w])/.test('a')
    return true.

Why is that?

2

Answers


  1. Basically
    /^(?=.*[w])$/ -> $/ -> takes the entire string for matching – if yes – return true

    /^(?=.*[w]). -> Here it checks for the first character matching – if yes – return true

    Login or Signup to reply.
  2. This pattern asserts a word character, but the match is an empty string ^$ so that will always be false:

    ^(?=.*w)$
    

    This pattern asserts a word character, which will be true for a, but also for a string like ab %

    ^(?=.*w)
    

    If you want to combine them and get a match for only a you can assert a word character followed by the end of the string inside the assertion:

    ^(?=w$)
    

    But in that case you don’t need an assertion, you can just match:

    ^w$
    
    console.log(/^(?=.*w)$/.test('a'));
    console.log(/^(?=.*w)/.test('a'));
    console.log(/^(?=w$)/.test('a'));
    console.log(/^w$/.test('a'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search