3 回答
TA贡献1852条经验 获得超7个赞
您可以使用split来提取部分(名称和值),并将Object.fromEntries这些对转换为一个对象。然后您可以通过该对象的属性访问每个值:
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);
请注意,在示例字符串中,EP没有对应的=,在这种情况下,返回的对象toObject将undefined分配给属性EP。要测试该EP属性是否实际存在,您可以使用in运算符:
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贡献1841条经验 获得超3个赞
因此,您使用不同的分隔符重新发明了查询。把它设为 & 你就可以使用内置的 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"));
如果你想用 ^留它,一个拆分和映射
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"]);
如果你只关心这 3 个值
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);
而且因为你似乎只关心一个值
const str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const val = str.match(/nicetomeetyou=(.{6})/)[1]
console.log(val);
TA贡献1815条经验 获得超6个赞
您可以将所有^
值替换为并通过URLSearchParams&
运行它以获取您要查找的值:
const str = "Hello=322484^nicetomeetyou=245454^howdoIdothis=11111a^EP";
const params = new URLSearchParams(str.replace(/\^/g, '&'))
console.log(params.get('nicetomeetyou'))
添加回答
举报