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

How to get an array of strings using regex for ternary operator?

There is a task to make a regular expression for a ternary operator without nesting. I’m stuck at this point. Help me please!

String for regex:

let str = "!(a == b) && (c == d) ? value1 : 'value2'"

The result of the script with regex:

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

let result = ["!(a == b) && (c == d)", "value1", "'value2'"]

The result is an array with strings. The line where the condition is a simple expression, without double question marks. Only logical operators.

I tried to do regex, but it didn’t work.

>Solution :

Try this one

let str = "!(a == b) && (c == d) ? value1 : 'value2'";

let regex = /([^\?]+)\s+\?\s+(.+?)\s+:\s+(.+)/;
let result = str.match(regex).slice(1);

console.log(result);

Here is the result :

["!(a == b) && (c == d)", "value1", "'value2'"]
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