I have the following strings:
'foo(123abc)bar(456def)'
// or
'foo(123abc) bar(456def)'
I need the JavaScript code to get the word that is to the left of the parentheses and the content that is inside them: (either of the two ways)
['foo', '123abc', 'bar', '456def']
// or
{
'foo': '123abc',
'bar': '456def'
}
I tried /\w\(([^\)]*)\)/.exec('foo(123abc)bar(456def)'), but the result was ['o(123abc)', '123abc']
I don’t know much about regex!
>Solution :
You can achieve that by replacing one of the parantheses with the other and then splitting the string by the remaining parantheses:
let result1 = 'foo(123abc)bar(456def)'.replaceAll(')', '(').split('(');
and you can apply a regex as well if you need to do so:
let result2 = 'foo(123abc)bar(456def)'.split(/(|)/);
In both cases you will have an empty string as the last element, so you will need to call result1.splice(-1, 1) or result2.splice(-1, 1) respectively.