简体   繁体   English

Javascript:将字符串转换为带有正则表达式的数组

[英]Javascript: Turn a String to an Array with a Regular Expression

I have some strings that look like arrays which I'd like to make into real arrays 我有一些看起来像数组的字符串,我想将它们制作成真实的数组

For example this string... 例如,这个字符串...

"['str1', 'str2', 'str3', 'str4']"

...I'd like to become and array of strings: ...我想成为和字符串数组:

['str1','str2','str3','str4']

I think what I'd need to do is run a RegExp on the string to get rid of the brackets ([]), single quotes (') and spaces so its just a string like: "str1,str2,str3,str4" and then simply run the split(',') method but I'm not sure how to make this RegExp 我认为我需要做的是在字符串上运行RegExp以除去括号([]),单引号(')和空格,因此它只是一个字符串,例如:“ str1,str2,str3,str4”然后只需运行split(',')方法,但我不确定如何制作此RegExp

Simplest way is to use JSON.parse . 最简单的方法是使用JSON.parse Strings inside JSON string have to be delimited by double quotes, like this. 像这样,JSON字符串中的字符串必须用双引号分隔。

result = JSON.parse('["str1", "str2", "str3", "str4"]'); 

This technique will work for null , any javascript object or any valid JSON object. 此技术适用于null ,任何javascript对象或任何有效的JSON对象。 You can read about JSON format here: 您可以在此处阅读有关JSON格式的信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

Don't reinvent the wheel! 不要重新发明轮子! Don't use custom regexes for solved problem. 不要使用自定义正则表达式解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM