How To Split String Which Is In The Form An Array Using Javascript?
I have a string in the form of an array. Like.., '['123', '456', '789']'; '['abc', 'xyz']' I want to access the elements inside that is; '123', '456'... How can I do this in Javasc
Solution 1:
Here you go;
let str = "['123', '456', '789']"let res = str.slice(str.indexOf('[') + 1, str.length - 1)
let result = res.split(', ')
let req = []
result.map(item => {
let i = item.replace(/'/g, '')
req.push(i)
})
console.log(req)
Nothing special here. Used the in-built function slice
to get the slice of the given string. Slice takes two args , starting index and end index. starting index character is included in the string, that is why, i am adding 1 to it to exclude '['. End index is excluded.
Then i splited the result at ,
, removed single quotes from every element. that is it.
Post a Comment for "How To Split String Which Is In The Form An Array Using Javascript?"