How can I match a whole word in JavaScript?

前端 未结 4 680
栀梦
栀梦 2020-11-22 02:37

I am trying to search a single whole word through a textbox. Say I search "me", I should find all occurrences of the word "me" in the text, but not "

4条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 03:04

    
    

    It's a bit hard to tell what you're trying to do here. What is the tttt variable supposed to do?

    Which string are you trying to search in? Are you trying to look for 2 within the string lookup? Then you would want:

    /\b2\b/.test(lookup)
    

    The following, from your regular expression, constructs a regular expression that consists of a word boundary, followed by the string "lookup" (not the value contained in the variable lookup), followed by a word boundary. It then tries to match this regular expression against the string "2", obtained by converting the number 2 to a string:

    (/\b(lookup)\b/g).test(2)
    

    For instance, the following returns true:

    (/\b(lookup)\b/g).test("something to lookup somewhere")
    

提交回复
热议问题