繁体   English   中英

如何修剪多个字符?

[英]How to trim multiple characters?

我有一个字符串如下

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

如果我修剪弦

example.trim()

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

但我想在这里输出some string ()() here 怎么实现呢?

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

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

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

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

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

/^(?:\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, "$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('-------') }) 

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

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

如果您想在修剪后只删除外部支架,则可以使用

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

最后修整是可选的其去除之间的空间(s也之间e)

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

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

 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)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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