Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 651
sertsedat Avatar asked Feb 03 '23 21:02

sertsedat


2 Answers

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('-------')
})
like image 111
mplungjan Avatar answered Feb 06 '23 11:02

mplungjan


You can use the regex to get the matched string, The below regex, matches the first character followed by characters or whitespaces and ending with a alphanumberic character

const example = ' ( some (string) ()()here )   ';
console.log(example.match(/(\w[\w\s.(.*)]+)\w/g));
like image 30
Shubham Khatri Avatar answered Feb 06 '23 09:02

Shubham Khatri