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());
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With