0

How to split String with pattern [123, 556, 9898] into arrays, in JavaScript

For example a String: str = "[123, 556, 9898]" Into an Array: arr = ["123", "556" ,"9898"];

21st Oct 2020, 7:43 AM
Azizbek Avazov
Azizbek Avazov - avatar
4 Respuestas
+ 4
let str = "[123, 234, 467]" str = str.replace(/(\[|\])/g, "").split(", ") console.log(str);
21st Oct 2020, 8:05 AM
maf
maf - avatar
+ 3
What i did: 1) removed [ and ] from string using regex, but u can also do it without regex: str = str.replace("[" "") str = str.replace("]", "") 2) I splitted the array with ", "
21st Oct 2020, 8:08 AM
maf
maf - avatar
+ 1
Are you sure that string has those square brackets? You could use String.split() method arr = str.split(",");
21st Oct 2020, 7:51 AM
Raj Chhatrala
Raj Chhatrala - avatar
0
yes, string has brackets, and they should be avoided.
21st Oct 2020, 7:56 AM
Azizbek Avazov
Azizbek Avazov - avatar