Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex expression to get data in this format

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading