3 回答

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以使用split來提取部分(名稱和值),并將Object.fromEntries這些對(duì)轉(zhuǎn)換為一個(gè)對(duì)象。然后您可以通過該對(duì)象的屬性訪問每個(gè)值:
const toObject = (str) =>
Object.fromEntries(str.split("^").map(eq => eq.split("=")));
// Demo
let str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
let obj = toObject(str);
console.log(obj.Hello);
請(qǐng)注意,在示例字符串中,EP沒有對(duì)應(yīng)的=,在這種情況下,返回的對(duì)象toObject將undefined分配給屬性EP。要測(cè)試該EP屬性是否實(shí)際存在,您可以使用in運(yùn)算符:
const toObject = (str) =>
Object.fromEntries(str.split("^").map(eq => eq.split("=")));
// Demo
let str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
let obj = toObject(str);
console.log("EP" in obj); // true

TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個(gè)贊
因此,您使用不同的分隔符重新發(fā)明了查詢。把它設(shè)為 & 你就可以使用內(nèi)置的 URLSearchParams
const str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const urlParams = new URLSearchParams(str.replace(/\^/g, '&'));
console.log(urlParams.get("Hello"));
console.log(urlParams.get("nicetomeetyou"));
console.log(urlParams.get("howdoIdothis"));
如果你想用 ^留它,一個(gè)拆分和映射
var str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const params = Object.fromEntries(str.split("^").map(s => s.split(/=/)));
console.log(params["Hello"]);
console.log(params["nicetomeetyou"]);
console.log(params["howdoIdothis"]);
如果你只關(guān)心這 3 個(gè)值
var str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP"
var re = /=([^\^]+)/g;
var out = [];
while(match = re.exec(str)) out.push(match[1]);
console.log(out);
而且因?yàn)槟闼坪踔魂P(guān)心一個(gè)值
const str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const val = str.match(/nicetomeetyou=(.{6})/)[1]
console.log(val);

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以將所有^
值替換為并通過URLSearchParams&
運(yùn)行它以獲取您要查找的值:
const str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const params = new URLSearchParams(str.replace(/\^/g, '&'))
console.log(params.get('nicetomeetyou'))
添加回答
舉報(bào)