-1

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 Javascript?

1
  • Make sure your have added the correct input and output to the question. JSON is not valid. Commented Jul 24, 2021 at 6:06

1 Answer 1

-2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.