Javascript Regex for a partial string match only

14,387

Solution 1

You want to use a non-word boundary \B here.

/\Batta|atta\B/

Solution 2

sp00m almost got it right

^(atta.+|.+atta|.+atta.+)$

Fiddle.

If whitespace is not allowed you could write

^(atta[\S]+|[\S]+atta|[\S]+atta[\S]+)$
Share:
14,387
maurya8888
Author by

maurya8888

Updated on June 05, 2022

Comments

  • maurya8888
    maurya8888 almost 2 years

    I need to write a JavaScript RegEx that matches only the partial strings in a word.

    For example if I search using the string 'atta'

    it should return

    true for khatta
    true for attari
    true for navrattan
    false for atta
    

    I am not able to figure how to get this done using one RegEx. Thanks!

  • sp00m
    sp00m almost 10 years
    Or even ^(atta.+|.+atta.*)$ ;)
  • chris97ong
    chris97ong almost 10 years
    Hmm...so atta gives false but atta gives true.
  • Per Hornshøj-Schierbeck
    Per Hornshøj-Schierbeck almost 10 years
    I think this is a much cleaner answer than mine
  • MaxArt
    MaxArt almost 10 years
    Good one. I may add that for test the capturing group is useless and memory consuming. I wonder if !/\batta\b/.test(string) isn't any faster...
  • Lee Kowalkowski
    Lee Kowalkowski almost 10 years
    @MaxArt would that not also match "foobar"? If you're really worried about capturing groups, use a non-capturing group: /(?:\Batta|atta\B)/
  • maurya8888
    maurya8888 almost 10 years
    I believe !/\batta\b/.test(string) will return true for "this too". I need a partial match at least.
  • MaxArt
    MaxArt almost 10 years
    Yep, /\batta\b/ would match strings that also don't contain "atta" at all - I guess OP doesn't want that. @LeeKowalkowski There's no need to have groups either, in this case.
  • Lee Kowalkowski
    Lee Kowalkowski almost 10 years
    @MaxArt oh how right you are! I seemed to have thought the brackets were always required for |. I will edit my answer (and a few regexes I have lying around ha ha)