Search code examples
javascriptregexstringtrim

How to trim multiple characters?


I have a string as follows

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

If I trim the string with

example.trim()

it will give me the output: ( some string ()() here )

But I want the output some string ()() here. How to achieve that?

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


Solution

  • You can use a regex for leading and trailing space/brackets:

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

    If the strings are optionally leading and/or trailing, you need to create some optional non-capturing groups

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