简体   繁体   中英

JavaScript Regex exclude leading and trailing spaces, but maintain inner-spaces

I have a string like this:

' hello world '

I would like to match groups ' ' , 'hello world' , and ' '

I can't figure out how to allow spaces in the middle of the regex, where they aren't anchored to end

My attempt ( http://regex101.com ) /(^\\s*)(.+)(\\s*$)/g

You can use this regex with 3 capturing groups:

/^(\s*)(\S+(?:\s+\S+)*)(\s*)$/

RegEx Demo

RegEx Breakup:

  • ^ : Start
  • (\\s*) : Match & capture starting white space (zero or more)
  • (\\S+(?:\\s+\\S+)*) : Match & capture middle string that may contain white spaces
  • (\\s*) : Match & capture ending white space (zero or more)
  • $ : End

Assuming your string is always spaces_words_spaces:

"   hello world   ".match(/^(\s+)(.*?)(\s+)$/)

Prints:

["   hello world   ", "   ", "hello world", "   ", index: 0, input: "   hello world   "]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM