Javascript 在第一个空格出现时拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10272773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split string on the first white space occurrence
提问by Luca
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",
]
回答by Trott
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).
请注意,如果根本没有空格,则第一行将返回一个空字符串,第二行将返回整个字符串。确保这是您在那种情况下想要的行为(或者那种情况不会出现)。
回答by georg
Javascript doesn't support lookbehinds, so split
is not possible. match
works:
Javascript 不支持lookbehinds,所以split
是不可能的。match
作品:
str.match(/^(\S+)\s(.*)/).slice(1)
Another trick:
另一个技巧:
str.replace(/\s+/, '\x01').split('\x01')
how about:
怎么样:
[str.replace(/\s.*/, ''), str.replace(/\S+\s/, '')]
and why not
那么为何不
reverse = function (s) { return s.split('').reverse().join('') }
reverse(str).split(/\s(?=\S+$)/).reverse().map(reverse)
or maybe
或者可能
re = /^\S+\s|.*/g;
[].concat.call(re.exec(str), re.exec(str))
2019 update: as of ES2018, lookbehinds are supported:
2019 年更新:从 ES2018 开始,支持lookbehinds:
str = "72 tocirah sneab"
s = str.split(/(?<=^\S+)\s/)
console.log(s)
回答by user1652176
In ES6 you can also
在 ES6 中,您还可以
let [first, ...second] = str.split(" ")
second = second.join(" ")
回答by Cliff Stanford
Late to the game, I know but there seems to be a very simple way to do this:
我知道比赛已经晚了,但似乎有一种非常简单的方法可以做到这一点:
const str = "72 tocirah sneab";
const arr = str.split(/ (.*)/);
console.log(arr);
This will leave arr[0]
with "72"
and arr[1]
with "tocirah sneab"
. Note that arr[2] will be empty, but you can just ignore it.
这将arr[0]
与"72"
和arr[1]
一起离开"tocirah sneab"
。请注意, arr[2] 将为空,但您可以忽略它。
For reference:
以供参考:
回答by Joseph
var arr = []; //new storage
str = str.split(' '); //split by spaces
arr.push(str.shift()); //add the number
arr.push(str.join(' ')); //and the rest of the string
//arr is now:
["72","tocirah sneab"];
but i still think there is a faster way though.
但我仍然认为有更快的方法。
回答by fpscolin
georg's solution is nice, but breaks if the string doesn't contain any whitespace. If your strings have a chance of not containing whitespace, it's safer to use .split and capturing groups like so:
georg 的解决方案很好,但如果字符串不包含任何空格,则会中断。如果您的字符串有可能不包含空格,则使用 .split 和捕获组更安全,如下所示:
str_1 = str.split(/\s(.+)/)[0]; //everything before the first space
str_2 = str.split(/\s(.+)/)[1]; //everything after the first space
回答by Daedalus
回答by Rotareti
Just split the string into an array and glue the parts you need together. This approach is very flexible, it works in many situations and it is easy to reason about. Plus you only need one function call.
只需将字符串拆分为一个数组并将您需要的部分粘合在一起。这种方法非常灵活,它适用于许多情况并且很容易推理。此外,您只需要一个函数调用。
arr = str.split(' '); // ["72", "tocirah", "sneab"]
strA = arr[0]; // "72"
strB = arr[1] + ' ' + arr[2]; // "tocirah sneab"
Alternatively, if you want to cherry-pick what you need directly from the string you could do something like this:
或者,如果您想直接从字符串中挑选您需要的内容,您可以执行以下操作:
strA = str.split(' ')[0]; // "72";
strB = str.slice(strA.length + 1); // "tocirah sneab"
Or like this:
或者像这样:
strA = str.split(' ')[0]; // "72";
strB = str.split(' ').splice(1).join(' '); // "tocirah sneab"
However I suggest the first example.
不过我建议第一个例子。
Working demo: jsbin
工作演示:jsbin
回答by acarito
Whenever I need to get a class from a list of classes or a part of a class name or id, I always use split() then either get it specifically with the array index or, most often in my case, pop() to get the last element or shift() to get the first.
每当我需要从类列表或类名或 id 的一部分中获取类时,我总是使用 split() 然后用数组索引专门获取它,或者在我的情况下最常见的是 pop() 来获取最后一个元素或 shift() 获得第一个。
This example gets the div's classes "gallery_148 ui-sortable" and returns the gallery id 148.
此示例获取 div 的类“gallery_148 ui-sortable”并返回画廊 ID 148。
var galleryClass = $(this).parent().prop("class"); // = gallery_148 ui-sortable
var galleryID = galleryClass.split(" ").shift(); // = gallery_148
galleryID = galleryID.split("_").pop(); // = 148
//or
galleryID = galleryID.substring(8); // = 148 also, but less versatile
I'm sure it could be compacted into less lines but I left it expanded for readability.
我确信它可以压缩成更少的行,但为了可读性,我将它扩展了。
回答by jim.richards
I needed a slightly different result.
我需要一个稍微不同的结果。
I wanted the first word, and what ever came after it - even if it was blank.
我想要第一个词,以及它后面的东西——即使它是空白的。
str.substr(0, text.indexOf(' ') == -1 ? text.length : text.indexOf(' '));
str.substr(text.indexOf(' ') == -1 ? text.length : text.indexOf(' ') + 1);
so if the input is oneword
you get oneword
and ''
.
所以如果输入是oneword
你得到oneword
和''
。
If the input is one word and some more
you get one
and word and some more
.
如果输入是one word and some more
你得到one
和word and some more
。