Search code examples
javascriptregexstringspace

How to match the start and end of a string?


I try to match space at the start and the end of string, I tried many regexes but nothing worked, this is my basic regex:

^\s\s$

Any help or hint please? I would like to not give me the answer directly, just useful hints will be useful.


Solution

  • Your current regex will match things like 2 spaces, because that's what your regex says:

    start of string, whitespace, whitespace, end of string

    To match spaces both at the start and at the end, you need to use the | to mean "or". If the whitespace is either at the start or the end, we match it:

    ^\s|\s$
    

    If you want to match multiple spaces:

    ^\s+|\s+$