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