Do you know the purpose of (^|\s) in the following expression?
/(^|\s)(apple|orange|lemon)(\s|$)/.test(foo);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
(^|\s)matches the start of the string or a whitespace character.So it will match if the string says “apple it is”, or if it says “I want an apple”.
Do note that in the first case, it will match “apple “, and in the second case it matches ” apple”.
Notice the extra space matched. If that behaviour is not desired, then a word boundary should be used instead (given by
\b).Eg:
That would allow all apples matched to match “apple” exactly (instead of ” apple ” or other variants).