const str = "[1,2,3,4],5,6";
const getArray = (str) => {
...
return arr;
}
console.log(getArray(str)); //[1,2,3,4]
[1,2,3,4]
is the expected array.
How can I get this one?
const str = "[1,2,3,4],5,6";
const getArray = (str) => {
...
return arr;
}
console.log(getArray(str)); //[1,2,3,4]
[1,2,3,4]
is the expected array.
How can I get this one?
You can use regex
for extracting the numbers enclosed by []
then run a map
for sanitize. Check this-
const str = "[1,2,3,4],5,6";
const getArray = str => {
const regex = /(\[([^\]]+)\])/;
const match = regex.exec(str);
return match?.[2] ? match[2].split(',').map(x => x.trim()) : [];
}
console.log(getArray(str));
This will give you an array of all arrays within your string.
const str = "[1,2,3,4],5,6";
const getArray = (str) => {
const ans = []
let stack = []
let isStack = true
for (let i = 0; i < str.length; i++) {
if (str[i] == '[') {
isStack = true;
} else if (str[i] == ']') {
isStack = false;
ans.push(stack)
stack = []
} else if (isStack && str[i] != ',') {
stack.push(parseInt(str[i]))
}
}
return ans;
}
console.log(getArray(str)) // [ [ 1, 2, 3, 4 ] ]
console.log(getArray(str)[0]) // [ 1, 2, 3, 4 ]
You can use the JavaScript method lastIndexOf() to find the [
and ]
.
This will give you all characters in-between [
and ]
.
Then you can use the split() method to convert the array.
Using map() and Number you can convert string to number
const str = "[1,2,3,4],5,6";
function getArray(str){
var myArray = str.substring(
str.lastIndexOf("[") + 1,
str.lastIndexOf("]")
);
return myArray.split(",").map(Number);
}
console.log(getArray(str));
Assuming that str contains exactly one pair of enclosing square brackets:
const getArray = (str) => {
const idxStart = str.indexOf('[') + 1
const idxEnd = str.indexOf(']')
arr = str.slice(idxStart, idxEnd)
return arr.split(',')
}
You can use RegEx
to match the string enclosed in []
const str = "[1,2,3,4],5,6";
const getArray = (str) => {
arr = str.match('/\[.*\]/')[0]
return arr;
}
console.log(getArray(str));