2

I am using jQuery & JavaScript!!

I have a string, for example

"cubic-bezier(0.25, 0, 0.25, 1), ease-in, ease-out, linear"

..and I want to split it into this array:

// (the following has no leading or trailing spaces:)

Array[4]
  0: cubic-bezier(0.25, 0, 0.25, 1)
  1: ease-in
  2: ease-out
  3: linear

..but instead I get:

Array[7]
  0: cubic-bezier(0.25
  1: 0
  2: 0.25
  3: 1)
  4: ease-in
  5: ease-out
  6: linear

I have attempted a dozen solutions, only to find that any way that I try it doesn't work thus far. Here are a few of my previous attempts:

var myString = "cubic-bezier(0.25, 0, 0.25, 1), ease-in, ease-out, linear";

myString.split(",(?![^\(\)]*>)");

myString.split('(?:\(.*?\))|(,)');

myString.split(",(?=[^\]]*(?:\[|$))");

myString.split(",(?![^()]*(?:\([^()]*\))?\))");

myString.split('/,(?![^()]*(?:\([^()]*\))?\)/g');

myString.split(",(?=(([^']*'){2})*[^']*$)(?=(([^\"]*\"){2})*[^\"]*$)(?![^()]*\\))");

I am familiar with basic regex rules, such as capture groups and selectors, but am still confused on lookaheads or how I would solve my current situation.

1 Answers1

8

Match any comma not inside parentheses

var myString = "cubic-bezier(0.25, 0, 0.25, 1), ease-in, ease-out, linear";

var parts    = myString.split(/\,\s?(?![^\(]*\))/);

console.log(parts)
/\,\s?(?![^\(]*\))/
  • \, matches the character , literally
  • \s? matches any whitespace character. The ? quantifier matches between zero and one times
  • (?![^\(]*\)) Negative Lookahead asserts that the regex does not match a single character not present in the list below
  • [^\(] Quantifier. Matches between zero and unlimited times, as many times as possible
  • \( matches the character ( literally
  • \) matches the character ) literally
adeneo
  • 312,895
  • 29
  • 395
  • 388