1

I have a string which looks like this: "foo, bar,baz"

I need your help with regexp to split it on commas that are surrounded by anything on both sides, e.g. ['foo, bar', 'baz']

1
  • 1
    Is the two-element result a typo or deliberate? Commented Oct 13, 2016 at 12:29

1 Answer 1

2

You may match all the substrings you need with /(?:\s,\S|\S,\s|[^,])+/g regex:

var regex = /(?:\s,\S|\S,\s|[^,])+/g;
var str = "foo, bar,baz";
console.log(str.match(regex));

See the regex demo

The regex matches 1+ occurrences of:

  • \s,\S - a whitespace, ,, non-whitespace
  • | - or
  • \S,\s - a non-whitespace, ,, whitespace
  • | - or -[^,] - a char other than ,
Sign up to request clarification or add additional context in comments.

Comments

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.