文字列ベースを最初の空白の出現に分割する最適化された正規表現を取得できませんでした。
var str="72 tocirah sneab";
私は取得する必要があります:
[
"72",
"tocirah sneab",
]
文字列ベースを最初の空白の出現に分割する最適化された正規表現を取得できませんでした。
var str="72 tocirah sneab";
私は取得する必要があります:
[
"72",
"tocirah sneab",
]
スペース文字のみ (タブやその他の空白文字ではなく) を気にし、最初のスペースの前のすべてと最初のスペースの後のすべてだけを気にする場合は、次のように正規表現なしで実行できます。
str.substring(0, str.indexOf(' ')); // "72"
str.substring(str.indexOf(' ') + 1); // "tocirah sneab"
スペースがまったくない場合、最初の行は空の文字列を返し、2 行目は文字列全体を返すことに注意してください。それがその状況で必要な動作であることを確認してください (またはその状況が発生しないことを確認してください)。
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)
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"];
しかし、私はまだもっと速い方法があると思います。
文字列を配列に分割し、必要な部分を接着するだけです。このアプローチは非常に柔軟で、多くの状況で機能し、簡単に推論できます。さらに、必要な関数呼び出しは 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
少し異なる結果が必要でした。
私は最初の単語が欲しかったのです。
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
word and some more
次の関数は、文を常に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;
}