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
497 views
in Technique[技术] by (71.8m points)

javascript - How do I split a string by whitespace and ignoring leading and trailing whitespace into an array of words using a regular expression?

I typically use the following code in JavaScript to split a string by whitespace.

"The quick brown fox jumps over the lazy dog.".split(/s+/);
// ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]

This of course works even when there are multiple whitespace characters between words.

"The  quick brown fox     jumps over the lazy   dog.".split(/s+/);
// ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]

The problem is when I have a string that has leading or trailing whitespace in which case the resulting array of strings will include an empty character at the beginning and/or end of the array.

"  The quick brown fox jumps over the lazy dog. ".split(/s+/);
// ["", "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog.", ""]

It's a trivial task to eliminate such empty characters, but I'd rather take care of this within the regular expression if that's at all possible. Does anybody know what regular expression I could use to accomplish this goal?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you are more interested in the bits that are not whitespace, you can match the non-whitespace instead of splitting on whitespace.

"  The quick brown fox jumps over the lazy dog. ".match(/S+/g);

Note that the following returns null:

"   ".match(/S+/g)

So the best pattern to learn is:

str.match(/S+/g) || []

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

...