如何解决如何将括号内用逗号分隔的字符串转换为Javascript中的数组?
如何将以下字符串转换为Javascript中的数组?原因是我想分别考虑这两个值。 字符串是元素中的值,当我将其打印到控制台时,我得到:('UYHN7687YTF09IIK762220G6','Second')
var data = elm.value;
console.log(data);
解决方法
您可以使用regex
实现此目标,例如:
const string = "('UYHN7687YTF09IIK762220G6','Second')";
const regex = /'(.*?)'/ig
// Long way
const array = [];
let match;
while (match = regex.exec(string)){
array.push(match[1]);
};
console.log(array)
// Fast way
console.log([...string.matchAll(regex)].map(i => i[1]))
,
let given_string = "('UYHN7687YTF09IIK762220G6','Second')";
// first remove the both ()
given_string = given_string.substring(1); // remove (
given_string = given_string.substring(0,given_string.length - 1); // remove )
let expected_array = given_string.split(',');
console.log(expected_array);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。