一只甜甜圈
2023-01-06 16:26:37
如何在 Javascript 中將以下字符串轉換為數組?原因是我想分別取兩個值。該字符串是一個元素的值,當我將它打印到控制臺時,我得到了:('UYHN7687YTF09IIK762220G6','Second')var data = elm.value;
console.log(data);
2 回答

慕少森
TA貢獻2019條經驗 獲得超9個贊
您可以使用 來實現這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]))

慕蓋茨4494581
TA貢獻1850條經驗 獲得超11個贊
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);
添加回答
舉報
0/150
提交
取消