簡體   English   中英

使用 Javascript 在字符串第一次出現時拆分字符串

[英]Split a string at the first occurence of a string using Javascript

我已經嘗試了其他線程的多種解決方案,但是當拆分標志也是一個字符串時,似乎沒有任何效果。 在這種情況下,我需要將第一個“ - ”(空格破折號空格)與字符串的 rest 分開,其中包含其他出現的“ - ”

var string = "1 - 000: 3 - loremipsum";

尋找結果數組:

[1][000: 3 - loremipsum]

您可以通過" - " 拆分以獲得以下形式的數組:

["1", "000 : 3", "loremipsum"]

Then you can use destructuring assignment to separate the first element and the rest of the array ( r ) from each other, and use a template literal to form a string, with the rest of the array ( r ) joined back together with a hyphen:

 const string = "1 - 000: 3 - loremipsum"; const [first, ...r] = string.split(" - "); const res = `[${first}][${r.join(" - ")}]`; console.log(res);

或者,如果您希望您的結果在一個數組中,您可以創建一個新數組而不是使用模板文字:

 const string = "1 - 000: 3 - loremipsum"; const [first, ...r] = string.split(" - "); const res = [first, r.join(" - ")]; console.log(res);

如果您想要預期的 output,簡單的 replace() 就足夠了

 var str = "1 - 000: 3 - loremipsum" console.log('['+str.replace(' - ', '][')+']')

您可以嘗試使用子字符串,因為您似乎是 javascript 的初學者。

var string = "1 - 000 : 3 - loremipsum";
var start = string.indexOf(" - "); // find the first ocurance of space dash space
var result = [];
result.push(string.substr(0, start)); // string before " - "
result.push(string.substr(start+3)); // string after " - "
console.log(result);

您可以在分隔符上拆分,然后在第一個元素之后加入所有元素:

const string = "1 - 000 : 3 - loremipsum"

const delimiter = " - "
const splitArray = string.split(delimiter)
const firstElement = splitArray[0]
const otherElementsJoined = splitArray.slice(1).join(delimiter)
const finalArray = [firstElement, otherElementsJoined]
console.log(finalArray)

您可以嘗試在此處使用match()

 var string = "1 - 000: 3 - loremipsum"; var first = string.match(/^(.*?) -/)[1]; var second = string.match(/^.*? - (.*)$/)[1]; var output = [first, second]; console.log(output);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM