最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - regex match if starts or ends with whitespaces - Stack Overflow

programmeradmin4浏览0评论

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?

update:

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).

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?

update:

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).

Share Improve this question edited Aug 10, 2017 at 18:49 cplus asked Aug 10, 2017 at 18:29 cpluscplus 1,1154 gold badges25 silver badges57 bronze badges 1
  • /^(\s.*|.*\s)$/ should work for you. – anubhava Commented Aug 10, 2017 at 18:52
Add a ment  | 

5 Answers 5

Reset to default 9

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./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

modify it to the regex below

(^\s+.*)|(.*\s+$)

you can check the demo

this could help you , see demo here

^\s+.*|.*\s+$
发布评论

评论列表(0)

  1. 暂无评论