如何修剪多个字符?

ser*_*dat 9 javascript regex string trim

我有一个字符串如下

const example = ' ( some string ()() here )   ';
Run Code Online (Sandbox Code Playgroud)

如果我修剪弦

example.trim()
Run Code Online (Sandbox Code Playgroud)

它会给我输出: ( some string ()() here )

但我想要输出some string ()() here.怎么实现呢?

const example = ' ( some string ()() here )   ';
console.log(example.trim());
Run Code Online (Sandbox Code Playgroud)

mpl*_*jan 6

您可以使用正则表达式来引导和尾随空格/括号:

/^\s+\(\s+(.*)\s+\)\s+$/g
Run Code Online (Sandbox Code Playgroud)

function grabText(str) { 
  return str.replace(/^\s+\(\s+(.*)\s+\)\s+$/g,"$1");
}

var strings = [
  '  ( some (string) here )   ',
  ' ( some string ()() here )   '];
  
strings.forEach(function(str) {
  console.log('>'+str+'<')
  console.log('>'+grabText(str)+'<')
  console.log('-------')
})
Run Code Online (Sandbox Code Playgroud)

如果字符串可选地是前导和/或尾随,则需要创建一些可选的非捕获组

/^(?:\s+\(\s+?)?(.*?)(?:\s+\)\s+?)?$/g
/^ - from start
  (?:\s+\(\s+?)? - 0 or more non-capturing occurrences of  ' ( '
                (.*?) - this is the text we want
                     (?:\s+\)\s+?)? - 0 or more non-capturing occurrences of  ' ) '
                                  $/ - till end
                                    g - global flag is not really used here
Run Code Online (Sandbox Code Playgroud)

function grabText(str) {
  return str.replace(/^(?:\s+\(\s+?)?(.*?)(?:\s+\)\s+?)?$/g, "$1");
}

strings = ['some (trailing) here )   ',
           ' ( some embedded () plus leading and trailing brakets here )   ',
           ' ( some leading and embedded ()() here'
];
strings.forEach(function(str) {
  console.log('>' + str + '<')
  console.log('>' + grabText(str) + '<')
  console.log('-------')
})
Run Code Online (Sandbox Code Playgroud)