skip to Main Content

I’m trying to select the spaces at the beginning and end of a quote that’s a part of a larger string. Once selected, I will remove these leading/trailing whitespaces. I need to do this without using trim().

Here are a bunch of strings with ideal solutions to better illustrate my point:

  1. red " blue " green! => red "blue" green!
  2. " red blue green " => "red blue green"
  3. " red " " blue " " green " => "red" "blue" "green"

This is the closest I’ve gotten to solving this problem:

s+(?=(?:(?:[^"]*"){2})*[^"]*"[^"]*$)

The Regex correctly locates the leading and ending whitespaces in the examples above, but it fails when multiple words are within the quotes. It only works when 1 word is within the quotes.

2

Answers


  1. If you want to remove these spaces, you can use

    s.replace(/" *([^"]*?) *"/g, '"$1"')
    

    See this demo at regex101 or a JS demo at tio.run


    The pattern is simple, it captures lazily any amount of non-quotes surrounded by optional space within quotes. It would do some superfluous replacements as well but won’t lose balance.

    Login or Signup to reply.
  2. If you need to support escaped quotes inside the string you can modify the @bobble bubble regex like this:

    s.replace(/" *((?:[^"\]|\")*?) *"/g, '"$1"')
    

    Here’s a preview on regex101.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search