182

文字列ベースを最初の空白の出現に分割する最適化された正規表現を取得できませんでした。

var str="72 tocirah sneab";

私は取得する必要があります:

[
    "72",
    "tocirah sneab",
]
4

15 に答える 15

383

スペース文字のみ (タブやその他の空白文字ではなく) を気にし、最初のスペースの前のすべてと最初のスペースの後のすべてだけを気にする場合は、次のように正規表現なしで実行できます。

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

スペースがまったくない場合、最初の行は空の文字列を返し、2 行目は文字列全体を返すことに注意してください。それがその状況で必要な動作であることを確認してください (またはその状況が発生しないことを確認してください)。

于 2012-04-22T22:50:38.707 に答える
71

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 の時点で、後読みがサポートされています。

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

于 2012-04-22T22:51:33.513 に答える
16
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"];

しかし、私はまだもっと速い方法があると思います。

于 2012-04-22T22:47:40.433 に答える
10

.replace を使用して、最初に出現したものだけを置き換えることもできます。

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

/g を省略します。

デモ

于 2012-04-22T22:54:43.383 に答える
2

文字列を配列に分割し、必要な部分を接着するだけです。このアプローチは非常に柔軟で、多くの状況で機能し、簡単に推論できます。さらに、必要な関数呼び出しは 1 つだけです。

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

于 2016-07-18T02:10:58.713 に答える
0

少し異なる結果が必要でした。

私は最初の単語が欲しかったのです。

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場合。oneword and some more

于 2015-04-10T11:16:35.603 に答える
-1

次の関数は、文を常に2 つの要素に分割します。最初の要素には最初の単語のみが含まれ、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;
}
于 2020-03-09T10:04:42.973 に答える