Regex to find comma followed by non-whitespace cha

2020-04-19 08:19发布

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.

2条回答
叼着烟拽天下
2楼-- · 2020-04-19 08:43

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

查看更多
【Aperson】
3楼-- · 2020-04-19 08:53

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.

查看更多
登录 后发表回答