0

I have an expression string from Angular [ngClass] directive containing multiple expressions with their corresponding key separated by a comma.

'background_orange':row.columnname.split(',')[4] == 1,'red:color':test==='testname','yellow:color':test==='testname'

When I try to split the above expression string into an array of individual expression with their using the .split(',') function it is splitting the in between the individual expressions.

Code:

var temp = "'background_orange':row.columnname.split(',')[4] == 1,'red:color':test==='testname','yellow:color':test==='testname'";

var result = temp.split(',');
console.log(result);

Output:

["'background_orange':row.columnname.split('", "')[4] == 1", "'red:color':test==='testname'", "'yellow:color':test==='testname'"]

Expected Result:

["'background_orange':row.columnname.split(',')[4] == 1", "'red:color':test==='testname'", "'yellow:color':test==='testname'"]

I tried to build regex to extract the individual expression but able to only extract the expression keys with the below regex

Regex:

'\b(.+?)':

What would be a regex to extract the above mentioned expected pattern

2 Answers 2

0

The following regex splits your string at , but ignores all , inside strings between " or ':

var temp = "'background_orange':row.columnname.split(',')[4] == 1,'red:color':test==='testname','yellow:color':test==='testname'";
var r = /(('[^']*')|("[^"]*")|[^,])+/g

var result = temp.match(r)
console.log(result);

Each match is a non-empty sequence of:

  1. ('[^']*') letters not being ' between '
  2. ("[^"]*") same as above with "
  3. [^,] a char not being ,
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Corylus. The Regex worked and the explanation is good and simple. Accepted answer.
0

((?:.*):(?:.*))\,((?:.*):(?:.*))\,((?:.*):(?:.*))

if the format is static the above regex format can be used.

1 Comment

Hi @Uthaya, Thank you for your answer. The format is not static and adding more expression is not providing the desired output for example 'background_orange':row.columnname.split(',')[4] == 1,'red:color':test==='testname','yellow:color':test==='testname','green:color':test==='testname','blue:color':test==='testname','white:color':test==='testname'. @Corylus regex is woking good by ignoring ',' inside quotes. Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.