Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

javascript - Split the sentences by ',' and remove surrounding spaces

I have this code:

var r = /(?:^s*([^s]*)s*)(?:,s*([^s]*)s*){0,}$/
var s = "   a   ,  b  , c "
var m = s.match(r)
m => ["   a   ,  b  , c ", "a", "c"]

Looks like the whole string has been matched, but where has "b" gone? I would rather expect to get:

["   a   ,  b  , c ", "a", "b", "c"]

so that I can do m.shift() with a result like s.split(',') but also with whitespaces removed.

Do I have a mistake in the regexp or do I misunderstand String.prototype.match?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a pretty simple & straightforward way to do this without needing a complex regular expression.

var str = "   a   ,  b  , c "
var arr = str.split(",").map(function(item) {
  return item.trim();
});
//arr = ["a", "b", "c"]

The native .map is supported on IE9 and up: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map


Or in ES6+ it gets even shorter:

var arr = str.split(",").map(item => item.trim());

And for completion, here it is in Typescript with typing information

var arr: string[] = str.split(",").map((item: string) => item.trim());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...