亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 JavaScript 中,如何拆分字符串中的每組字符?

在 JavaScript 中,如何拆分字符串中的每組字符?

MMMHUHU 2023-08-10 15:56:22
問題在 JavaScript 中,我可以在字符串上使用哪種正則表達式模式或方法String.prototype.split()來在特定字符之間重復拆分?例子如果我有下面的字符串,'a="https://google.com/" b="Johnny Bravo" c="1" d="2" charset="z"'...我想在每個空格和雙引號之間拆分,然后將它們存儲到一個數組中,如下所示['a="https://google.com/"', 'b="Johnny Bravo"', 'c="1"', 'd="2"', 'charset="z"']試圖我在下面有一個復雜的想法。我必須搜索每個術語并將它們添加到數組中。但是,只有當我提前知道關鍵值時它才有效。// if I do findAttribute(ABOVE_STRING, 'a'),// I'll get 'a="https://google.com/"'// then I can add it to an arrayfindAttribute(content, target) {   if(!content || content === '') return {};   let ind_val = content.indexOf("\"", ind_attr+`${target}+"=\""`.length);   return content.slice(ind_attr,ind_val+1);}如果我嘗試使用下面的方法分割每個空間STRING.split(/\s+/g)它將在字符串的錯誤部分進行分割['a="https://google.com/"', 'b="Johnny', 'Bravo', 'c="1"', 'd="2"', 'charset="z"']
查看完整描述

3 回答

?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

我的做法:


const stringToProcess = '\'a="https://google.com/" b="Johnny Bravo" c="1" d="2" charset="z"\'';


const pair = /(\w+)="([^"]*)"/g;


const attributes = {};

while (true) {

  const match = pair.exec(stringToProcess);

  if (!match) break;

  

  const [, key, value] = match;

  attributes[key] = value;

}


console.log(attributes);


/*

{

  "a": "https://google.com/",

  "b": "Johnny Bravo",

  "c": "1",

  "d": "2",

  "charset": "z"

}

*/


查看完整回答
反對 回復 2023-08-10
?
達令說

TA貢獻1821條經驗 獲得超6個贊

如果你有一個固定的結構,那么如果你積極地匹配項目的結構,這種事情會效果更好。所以你可以做類似的事情...

'a="https://google.com/" b="Johnny Bravo" c="1" d="2" charset="z"'.match(/\w+=".*?"/gm)


查看完整回答
反對 回復 2023-08-10
?
萬千封印

TA貢獻1891條經驗 獲得超3個贊

你正在尋找的是一個對象。您需要將初始字符串拆分為數組,然后將其從數組中轉換為對象。我會這樣做:


const str = 'a="https://google.com/" b="Johnny Bravo" c="1" d="2" charset="z"';

// Split using RegEx

const arr = str.match(/\w+=(?:"[^"]*"|\d*|true|false)/g);

// Create a new object.

const obj = {};

// Loop through the array.

arr.forEach(it => {

? // Split on equals and get both the property and value.

? it = it.split("=");

? // Parse it because it may be a valid JSON, like a number or string for now.

? // Also, I used JSON.parse() because it's safer than exec().

? obj[it[0]] = JSON.parse(it[1]);

});

// Obj is done.

console.log(obj);


上面給了我:


{

? "a": "https://google.com/",

? "b": "Johnny Bravo",

? "c": "1",

? "d": "2",

? "charset": "z"

}

您可以使用類似obj.charsetand 的東西,這會為您zobj.b為您提供Johnny Bravo。


查看完整回答
反對 回復 2023-08-10
  • 3 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號