为了账号安全,请及时绑定邮箱和手机立即绑定

在 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 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信