How to trim multiple characters?
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('-------')
})
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));