0

window.eval("['bcs/abc/xyz.pdf', 'bcs/abc/xyz.pdf']"); gives output array object with urls how to do this without using eval, any elegant solution? Json.parse is not working in this scenario.

3
  • 1
    If your array elements would be enclosed in double quotes, then you could use JSON.parse('["bcs/abc/xyz.pdf", "bcs/abc/xyz.pdf"]') Commented Oct 1, 2020 at 7:54
  • 4
    JSON.parse is not working because it's not valid JSON. The most elegant solution is to make sure whatever is producing that value is producing valid JSON. Post-fixing the wrong data is pretty much always the wrong approach. Commented Oct 1, 2020 at 7:54
  • this is not JSON encoded string. you directly put an array in ' quote. Commented Oct 1, 2020 at 7:59

2 Answers 2

1

You really need to fix the server, but if you cannot then

const getArr = str => JSON.parse(
  `{"arr":${
  str.replace(/'/g,'"')
  }}`
)["arr"];
  
const arr = getArr(`['bcs/abc/xyz.pdf', 'bcs/abc/xyz.pdf']`)
console.log(arr)

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

Comments

0

You can try to parse it manually using regex

"['bcs/abc/xyz.pdf', 'bcs/abc/xyz.pdf']".replace(/^\[|"|'|\]$/g, '').split(/,\s?/)

Here regex used to replace brackets, after which you can split it using comma and zero or multiple white spaces as separator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.