Regex to find comma followed by non-whitespace cha

2020-04-19 08:28发布

问题:

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:

  • one
  • two, three

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.

回答1:

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)'))
);



回答2:

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.