Regex to remove spaces between '[' and ']'

前端 未结 3 1520
囚心锁ツ
囚心锁ツ 2020-12-07 03:22

I have been breaking my head on this for sometime now. In javascript I have a string expression where I need to remove the spaces between \'[\' and \']\'.

For examp

相关标签:
3条回答
  • 2020-12-07 03:43

    If brackets are always balanced correctly and if they are never nested, then you can do it:

    result = subject.replace(/\s+(?=[^[\]]*\])/g, "");
    

    This replaces whitespace characters if and only if there is a ] character ahead in the string with no intervening [ or ] characters.

    Explanation:

    \s+       # Match whitespace characters
    (?=       # if it's possible to match the following here:
     [^[\]]*  # Any number of characters except [ or ]
     \]       # followed by a ].
    )         # End of lookahead assertion.
    
    0 讨论(0)
  • 2020-12-07 03:43

    You can use this

    "[first name] + [ last name ] + calculateAge()".gsub(/\s+/, "")
    

    This works in ruby

    0 讨论(0)
  • 2020-12-07 03:46

    Try

    "[first name] + [ last name ] + calculateAge()".replace(/\[.*?\]/g, function(string) {
        return string.replace(/\s/g, '');
    })
    

    Demo: Fiddle

    0 讨论(0)
提交回复
热议问题