You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript:将字符串形式的数组转换为字符串数组

解决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:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 22:28:12