I’m trying to put together a js flavor of regex to match a string like in the following examples where there may be a whitespace at the front or back of the string, or both front and back. But not within the string
Examples:
'Z5LW-KRT2' MATCH
' Z5LW-krt2' MATCH
'Z5LW-KRT2 ' MATCH
' Z5LW-KRT2 ' MATCH
' Z5LW-K RT2 ' NO MATCH
So far i have come up with the below which matches if there is no whitespace anywhere, but i cant figure out how to include white space at the beginning or end but not within like in the examples
^[A-Za-z0-9\-]+$
>Solution :
You should add \s* to match spaces so the result regex should look like ^\s*[A-Za-z0-9\-]+\s*$ and even you can reduce it to ^\s*[\w\-]+\s*$ if you want to use the build-in class \w.