如何trim多个字符?

How to trim multiple characters?

我有一个字符串如下

const example = ' ( some string ()() here )   ';

如果我 trim 带有

的字符串
example.trim()

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

但我想要输出 some string ()() here。如何实现?

const example = ' ( some string ()() here )   ';
console.log(example.trim());

您可以使用正则表达式作为前导和尾随 space/brackets:

/^\s+\(\s+(.*)\s+\)\s+$/g

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

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

如果字符串可选地前导and/or尾随,您需要创建一些可选的非捕获组

/^(?:\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

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

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('-------')
})

您可以使用正则表达式来获取匹配的字符串,下面的正则表达式匹配第一个字符后跟字符或空格并以字母数字字符结尾

const example = ' ( some (string) ()()here )   ';
console.log(example.match(/(\w[\w\s.(.*)]+)\w/g));

  const str = ' ( some ( string ) here ) '.replace(/^\s+\(\s+(.*)\s+\)\s+$/g,'');
 console.log(str);

您可以使用递归方法并指定您希望 trim 字符串的次数。这也适用于圆括号以外的东西,例如方括号:

const example = ' ( some string ()() here )   ';
const exampleTwo = ' [  This, is [some] text    ]   ';

function trim_factor(str, times) {
  if(times == 0) {
    return str;
  }
  str = str.trim();
  return str.charAt(0) + trim_factor(str.substr(1, str.length-2), times-1) + str.charAt(str.length-1);
}

console.log(trim_factor(example, 2));
console.log(trim_factor(exampleTwo, 2));

如果您只想删除 trim 之后的外括号,您可以使用

var input = ' ( some string ()() here )   '.trim();
if( input.charAt(0) == '(' && input.charAt(input.length-1) == ')') {

var result = input.slice(1, -1).trim()
 console.log(result)
}

最后一个 trim 是可选的,它删除 (s 之间的 space 以及 e)[=15= 之间的 space ]