JavaScript:将字符串形式的数组转换为字符串数组
Got it, let's break down why your initial attempts with JSON.parse() didn't work and fix this step by step.
The root issue here is that your string uses single quotes (') for the array elements, but JSON strictly requires double quotes (") for string values. That's why JSON.parse("['one', 'two']") throws an error—it doesn't conform to valid JSON syntax.
Here are a few reliable ways to convert this string into a proper array:
1. Replace single quotes with double quotes, then use JSON.parse (Recommended)
This is the safest approach if your array elements don't contain single quotes themselves. We'll globally replace all single quotes in the string with double quotes to make it valid JSON, then parse it:
const myString = "['one', 'two']"; // Replace all single quotes with double quotes const validJsonString = myString.replace(/'/g, '"'); const myArray = JSON.parse(validJsonString); console.log(myArray); // Output: ['one', 'two'] console.log(typeof myArray); // Output: object
2. Use eval() (Only for trusted input!)
If you're 100% sure the input string comes from a trusted source (no risk of malicious code), you can use eval() to directly execute the string as JavaScript code:
const myString = "['one', 'two']"; const myArray = eval(myString); console.log(myArray); // Output: ['one', 'two'] console.log(typeof myArray); // Output: object
Important note: Never use eval() with untrusted input—it can execute arbitrary code and pose a serious security risk.
3. Use Function constructor (Alternative to eval)
This works similarly to eval() but wraps the string in a function that returns the array, which is slightly cleaner (but still carries the same security risks as eval for untrusted input):
const myString = "['one', 'two']"; const myArray = new Function(`return ${myString}`)(); console.log(myArray); // Output: ['one', 'two'] console.log(typeof myArray); // Output: object
Final Recommendation
Stick with the first method (replace quotes + JSON.parse) whenever possible—it's the most secure and avoids the risks associated with eval() or Function constructors. If your array elements might contain single quotes (e.g., ['don\'t', 'two']), you'll need to handle escaped quotes first, but for the basic case you described, the replace method works perfectly.
内容的提问来源于stack exchange,提问作者user3180997

