简体   繁体   English

在第一个空格出现时拆分字符串

[英]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",
]

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.substring(0, str.indexOf(' ')); // "72"
str.substring(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).确保这是您在那种情况下想要的行为(或者这种情况不会出现)。

Javascript doesn't support lookbehinds, so split is not possible. Javascript 不支持后视,因此无法split match works: 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)

In ES6 you can also在 ES6 中,您还可以

let [first, ...second] = str.split(" ")
second = second.join(" ")

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" .这将使arr[0]带有"72"arr[1]带有"tocirah sneab" Note that arr[2] will be empty, but you can just ignore it.请注意, arr[2] 将为空,但您可以忽略它。

For reference:以供参考:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#Capturing_parentheses https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#Capturing_parentheses

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.但我仍然认为有一种更快的方法。

georg's solution is nice, but breaks if the string doesn't contain any whitespace. georg 的解决方案很好,但如果字符串不包含任何空格,则会中断。 If your strings have a chance of not containing whitespace, it's safer to use .split and capturing groups like so:如果您的字符串有可能不包含空格,则使用 .split 并像这样捕获组会更安全:

str_1 = str.split(/\s(.+)/)[0];  //everything before the first space
str_2 = str.split(/\s(.+)/)[1];  //everything after the first space

You can also use .replace to only replace the first occurrence,您也可以使用 .replace 仅替换第一次出现,

​str = str.replace(' ','<br />');

Leaving out the /g.省略 /g。

DEMO演示

I'm not sure why all other answers are so complicated, when you can do it all in one line, handling the lack of space as well.我不确定为什么所有其他答案都如此复杂,当您可以在一行中完成所有操作时,还可以处理空间不足的问题。

As an example, let's get the first and "rest" components of a name:例如,让我们获取名称的第一个和“其余”部分:

 const [first, rest] = 'John Von Doe'.split(/\s+(.*)/); console.log({ first, rest }); // As array const components = 'Surma'.split(/\s+(.*)/); console.log(components);

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

Another simple way:另一种简单的方法:

str = 'text1 text2 text3';
strFirstWord = str.split(' ')[0];
strOtherWords = str.replace(strFirstWord + ' ', '');

Result:结果:

strFirstWord = 'text1';
strOtherWords = 'text2 text3';

我使用.split(" ")[0]来获取空格前的所有字符。

productName.split(" ")[0]

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.我确信它可以压缩成更少的行,但为了便于阅读,我将其扩展。

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 and word and some more

Most of the answers above search by space, not whitespace.上面的大多数答案都是按空格而不是空格搜索的。 @georg's answer is good. @georg 的回答很好。 I have a slightly different version.我有一个稍微不同的版本。

s.trim().split(/\s(.*)/).splice(0,2)

I'm not sure how to tell which is most efficient as the regexp in mine is a lot simpler, but it has the extra splace.我不确定如何判断哪个最有效,因为我的正则表达式要简单得多,但它有额外的空间。

(@georg's for reference is s.split(/(?<=^\S+)\s/) ) (@georg 的参考是s.split(/(?<=^\S+)\s/)

The question doesn't specify how to handle no whitespace or all whitespace, leading or trailing whitespace or an empty string, and our results differ subtly in those cases.该问题没有指定如何处理无空格或所有空格、前导或尾随空格或空字符串,在这些情况下,我们的结果略有不同。

I'm writing this for a parser that needs to consume the next word, so I prefer my definition, though @georg's may be better for other use cases.我正在为需要使用下一个单词的解析器编写此代码,因此我更喜欢我的定义,尽管 @georg 可能更适合其他用例。

input.        mine              @georg
'aaa bbb'     ['aaa','bbb']     ['aaa','bbb']
'aaa bbb ccc' ['aaa','bbb ccc'] ['aaa','bbb ccc']
'aaa '        [ 'aaa' ]         [ 'aaa', '' ]
' '           [ '' ]            [ ' ' ]
''            ['']              ['']
' aaa'        ['aaa']           [' aaa']
"72 tocirah sneab".split(/ (.*)/,2)

产生指定的结果

[ '72', 'tocirah sneab' ]

The following function will always split the sentence into 2 elements.以下函数将始终将句子分成 2 个元素。 The first element will contain only the first word and the second element will contain all the other words (or it will be a empty string).第一个元素将仅包含第一个单词,第二个元素将包含所有其他单词(或者它将是一个空字符串)。

var arr1 = split_on_first_word("72 tocirah sneab");       // Result: ["72", "tocirah sneab"]
var arr2 = split_on_first_word("  72  tocirah sneab  ");  // Result: ["72", "tocirah sneab"]
var arr3 = split_on_first_word("72");                     // Result: ["72", ""]
var arr4 = split_on_first_word("");                       // Result: ["", ""]

function split_on_first_word(str)
{
    str = str.trim();  // Clean string by removing beginning and ending spaces.

    var arr = [];
    var pos = str.indexOf(' ');  // Find position of first space

    if ( pos === -1 ) {
        // No space found
        arr.push(str);                // First word (or empty)
        arr.push('');                 // Empty (no next words)
    } else {
        // Split on first space
        arr.push(str.substr(0,pos));         // First word
        arr.push(str.substr(pos+1).trim());  // Next words
    }

    return arr;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM