OstrichGlue
OstrichGlue

Reputation: 345

Regex to find comma followed by non-whitespace characters

I'm trying to use the JS split() function to split on commas that are followed by non-whitespace, while ignoring commas with any whitespace after.

For example, the string "one, two, three", should not be split at all, while "one,two, three" should be split into:

I've tried using .split(',\\S') .split(',(?=\\S)")') and other variations, but haven't had any luck with getting it to split the way I want.

Upvotes: 3

Views: 2939

Answers (2)

saarrrr
saarrrr

Reputation: 2877

I got it working with this.

let s = 'one,two, three';
s.replace(', ', '|').split(',').map(x => x.replace('|', ', '));

Replace pipe with whatever works for you.

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115232

Use it with regex

str.split(/,(?=\S)/)

or parse the regex string to convert

str.split(new RegExp(',(?=\\S)'))

var str = 'a,b,c, d,e, f';

console.log(
  str.split(/,(?=\S)/)
);
console.log(
  str.split(new RegExp(',(?=\\S)'))
);

Upvotes: 4

Related Questions