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

javascript - Split string on the first white space occurrence

I didn't get an optimized regex that split me a String basing into the first white space occurrence:

var str="72 tocirah sneab";

I need to get:

[
    "72",
    "tocirah sneab",
]
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 only care about the space character (and not tabs or other whitespace characters) and only care about everything before the first space and everything after the first space, you can do it without a regular expression like this:

str.substr(0,str.indexOf(' ')); // "72"
str.substr(str.indexOf(' ')+1); // "tocirah sneab"

Note that if there is no space at all, then the first line will return an empty string and the second line will return the entire string. Be sure that is the behavior that you want in that situation (or that that situation will not arise).

Somewhat pedantic update: Although it is supported in effectively all browsers as well as Node.js, deno, etc., String.prototype.substr() has never been added normatively to the ECMAScript spec. Practically, this is unlikely to affect you. However, if it bothers you (or if you are running in some resource-constrained environment that doesn't have String.prototype.substr() for some reason), you can use one of the many other fine answers people have provided on this question. String.prototype.slice() is a pretty good substitute but be careful of the weirdness that ensues if indexOf() returns -1 for the second argument to slice(). (It will truncate the last character of the string.) Personally, I like the regexp lookbehind solution at the end of @georg's answer, but that won't work for very old browsers, so be aware of that.


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

...