簡體   English   中英

在第一個空格出現時拆分字符串

[英]Split string on the first white space occurrence

我沒有得到優化的正則表達式,它根據第一個空格出現將我拆分為字符串:

var str="72 tocirah sneab";

我需要得到:

[
    "72",
    "tocirah sneab",
]

如果您只關心空格字符(而不是制表符或其他空白字符)並且只關心第一個空格之前的所有內容以及第一個空格之后的所有內容,那么您可以在沒有這樣的正則表達式的情況下執行此操作:

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

請注意,如果根本沒有空格,則第一行將返回一個空字符串,第二行將返回整個字符串。 確保這是您在那種情況下想要的行為(或者這種情況不會出現)。

Javascript 不支持后視,因此無法split match作品:

str.match(/^(\S+)\s(.*)/).slice(1)

另一個技巧:

str.replace(/\s+/, '\x01').split('\x01')

怎么樣:

[str.replace(/\s.*/, ''), str.replace(/\S+\s/, '')]

那么為何不

reverse = function (s) { return s.split('').reverse().join('') }
reverse(str).split(/\s(?=\S+$)/).reverse().map(reverse)

或者可能

re = /^\S+\s|.*/g;
[].concat.call(re.exec(str), re.exec(str))

2019 年更新:從 ES2018 開始,支持lookbehinds:

 str = "72 tocirah sneab" s = str.split(/(?<=^\S+)\s/) console.log(s)

在 ES6 中,您還可以

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

我知道游戲遲到了,但似乎有一種非常簡單的方法可以做到這一點:

 const str = "72 tocirah sneab"; const arr = str.split(/ (.*)/); console.log(arr);

這將使arr[0]帶有"72"arr[1]帶有"tocirah sneab" 請注意, arr[2] 將為空,但您可以忽略它。

以供參考:

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"];

但我仍然認為有一種更快的方法。

georg 的解決方案很好,但如果字符串不包含任何空格,則會中斷。 如果您的字符串有可能不包含空格,則使用 .split 並像這樣捕獲組會更安全:

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

您也可以使用 .replace 僅替換第一次出現,

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

省略 /g。

演示

我不確定為什么所有其他答案都如此復雜,當您可以在一行中完成所有操作時,還可以處理空間不足的問題。

例如,讓我們獲取名稱的第一個和“其余”部分:

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

只需將字符串拆分為一個數組並將您需要的部分粘合在一起。 這種方法非常靈活,它適用於許多情況並且很容易推理。 另外,您只需要一個函數調用。

arr = str.split(' ');             // ["72", "tocirah", "sneab"]
strA = arr[0];                    // "72"
strB = arr[1] + ' ' + arr[2];     // "tocirah sneab"

或者,如果您想直接從字符串中挑選您需要的內容,您可以執行以下操作:

strA = str.split(' ')[0];                    // "72";
strB = str.slice(strA.length + 1);           // "tocirah sneab"

或者像這樣:

strA = str.split(' ')[0];                    // "72";
strB = str.split(' ').splice(1).join(' ');   // "tocirah sneab"

但是我建議第一個例子。

工作演示: jsbin

另一種簡單的方法:

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

結果:

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

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

productName.split(" ")[0]

每當我需要從類列表或類名或 id 的一部分中獲取類時,我總是使用 split() 然后使用數組索引專門獲取它,或者在我的情況下最常見的是 pop() 來獲取最后一個元素或 shift() 獲得第一個。

此示例獲取 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 

我確信它可以壓縮成更少的行,但為了便於閱讀,我將其擴展。

我需要一個稍微不同的結果。

我想要第一個詞,以及它之后的內容——即使它是空白的。

str.substr(0, text.indexOf(' ') == -1 ? text.length : text.indexOf(' '));
str.substr(text.indexOf(' ') == -1 ? text.length : text.indexOf(' ') + 1);

所以如果輸入是oneword你會得到oneword''

如果輸入是one word and some more ,你會得到one and word and some more

上面的大多數答案都是按空格而不是空格搜索的。 @georg 的回答很好。 我有一個稍微不同的版本。

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

我不確定如何判斷哪個最有效,因為我的正則表達式要簡單得多,但它有額外的空間。

(@georg 的參考是s.split(/(?<=^\S+)\s/)

該問題沒有指定如何處理無空格或所有空格、前導或尾隨空格或空字符串,在這些情況下,我們的結果略有不同。

我正在為需要使用下一個單詞的解析器編寫此代碼,因此我更喜歡我的定義,盡管 @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' ]

以下函數將始終將句子分成 2 個元素。 第一個元素將僅包含第一個單詞,第二個元素將包含所有其他單詞(或者它將是一個空字符串)。

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