Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...