我有這樣一個字串
a = "this is just an example"。
如果我用
split(" "/span>,1)
它將把第一個字列印成一個陣列。
我的問題是,我怎樣才能只把第二個字串分割成一個陣列呢?
CodePudding
使用2的限制,然后從第二個元素開始切分。
。a = "這只是一個例子"。
console.log(a. split(" ", 2).slice(1) ;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
或者以2為限分割字串,然后使用一個只包含第二個元素的陣列字面。
。a = "這只是一個例子"。
console.log([a. split(" ", 2)[1]];
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
一個更好的方法是在空格上分割&這將給你一個字串陣列,選擇你想要的索引&進一步分割它
注意:陣列索引從0開始,而不是從1開始,所以如果你想得到第二個字串,你將不得不使用索引1,而不是2。const a = "this is just an example";
const secondWordArr = a.split(' ')[1] 。 split('')。
//secondWordArr表示秒字的字符陣列。
console.log(secondWordArr); // Output [ 'i', 's' ]
解釋 :
a.split(' ') // this split the string into an array of strings/words
a.split(' ')[1] // access the second string in the array of split stringings/words
a.split(' '/span>)[1]。 split('') //將第二個字串從字串/字的陣列中分割成一個單獨的陣列//。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/324467.html
標籤:
