Javascript Regex Splitting Words in a Comma Separated String

Javascript regex splitting words in a comma separated string

Use a negated character class:

/([^,]+)/g

will match groups of non-commas.

< a = 'hi,mr.007,bond,12:25PM'
> "hi,mr.007,bond,12:25PM"
< b=/([^,]+)/g
> /([^,]+)/g
< a.match(b)
> ["hi", "mr.007", "bond", "12:25PM"]

RegEx expression to split a string on comma with a condition in JavaScript

Assuming you only ever would have to worry about excluding commas inside singly-nested parentheses, we can try splitting on the following regex pattern:

\s*,\s*(?![^(]*\))

This says to split on comma, surrounded on both sides by optional whitespace, so long as we can't look forward and encounter a closing ) parenthesis without also first seeing an opening ( one. This logic rules out the comma inside c=add(3,b), because that particular comma hits a ) first without seeing the opening one (.

var str = "a , b=10 , c=add(3,b) , d"parts = str.split(/\s*,\s*(?![^(]*\))/);console.log(parts);

REGEX: split javascript strings - ignore commas in nested strings and object-likes

You can use this regex to split on commas not under curley braces by using negative look ahead to ensure , is not contained in curley braces.

,(?![^{}]*\})

Demo, https://regex101.com/r/nGmRof/2

Here is a javascript code for demonstrating same.

var str = ['2,5,4','2,{"name": [2,3]}',' 2,{"key": "value", "key2":"value2" } '];for (i=0;i<str.length;i++) {    console.log(str[i] + " --> split into following");    str[i] = str[i].split(/,(?![^{}]*\})/);    for (j = 0; j < str[i].length; j++) {         console.log(str[i][j]);    }    console.log('\n\n');    }

How I can split string by comma and/or new line and/or whitespace

You need to split on either a comma surrounded by some number of white-space characters, or just one or more white-space characters:

let strs = ['o@gmail.com b@gmail.com c@gmail.om','o@gmail.com, b@gmail.com,c@gmail.com','o@gmail.com,\n\ b@gmail.com, c@gmail.com'];
console.log(strs.map(s => s.split(/\s*,\s*|\s+/)))

Regex to split a comma separated css class names string into array