I need to match my string if it starts with any number of whitespaces or ends with any number of spaces:
my current regex includes also the spaces inbetween:
(^|\s+)|(\s+|$)
how can I fix it to reach my goal?
this doesn't work, because it matches the spaces. I want to select the whole string or line rather, if it starts with or ends with whitespace(s).
The RegExp \s Metacharacter in JavaScript is used to find the whitespace characters. The whitespace character can be a space/tab/new line/vertical character. It is same as [ \t\n\r].
You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs).
\W means "non-word characters", the inverse of \w , so it will match spaces as well.
Spaces can be found simply by putting a space character in your regex. Whitespace can be found with \s . If you want to find whitespace between words, use the \b word boundary marker.
modify it to the following
(^\s+)|(\s+$)
Based on modified OP, Use this Pattern ^\s*(.*?)\s*$
Demo look at capturing group #1
^ # Start of string/line
\s # <whitespace character>
* # (zero or more)(greedy)
( # Capturing Group (1)
. # Any character except line break
*? # (zero or more)(lazy)
) # End of Capturing Group (1)
\s # <whitespace character>
* # (zero or more)(greedy)
$ # End of string/line
You can use this: https://regex101.com/r/gTQS5g/1
^\s|\s$
Or with .trim()
you could do without the regex:
myStr !== myStr.trim()
No need to create groups. You can create one alternation.
^\s+|\s+$
Live demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With