[英]Conditionally splitting string into array
I have a small piece of code that needs to split a string into a javascript object. 我有一小段代码需要将字符串拆分为javascript对象。
The resulting object need to look something like this: 生成的对象需要看起来像这样:
var myObject = {
valueOne: value,
valueTwo: value,
arrayOfValues: [values]
}
The strings that need to be converted come in two different formats. 需要转换的字符串有两种不同的格式。 Those formats look like:
这些格式如下:
1) "MyValues are ('1','2','3')"
--this would be translated into : 1)
"MyValues are ('1','2','3')"
这将被翻译成:
var myObject = {
valueOne: myValues,
valueTwo: are,
arrayOfValues: [1,2,3]
}
or 2) "MyValue="1""
--this would be translated into : 或2)
"MyValue="1""
这将被翻译成:
var myObject = {
valueOne: myValue,
valueTwo: =,
arrayOfValues: [1]
}
I know I can split this string like so: 我知道我可以像这样拆分这个字符串:
var arr[] = myString.split(" ");
But deciding which splitter to use based on the makeup of the string, then converting it into a javascript object is a world unknown to me. 但是根据字符串的构成决定使用哪个拆分器,然后将其转换为javascript对象是我不知道的世界。
Thanks for your help. 谢谢你的帮助。
EDIT -- I made a small mistake with example number two 编辑-我犯了一个小错误与例如二号
I updated it so that it's correct. 我更新了它,这是正确的。 -- The string I'm receiving is in the format of:
- 我收到的字符串格式为:
`"MyValue="1""`
samy-delux, thanks for your help! samy-delux,谢谢你的帮助! That works great, but the change to this second string breaks your example.
这很好用,但是对第二个字符串的更改打破了你的榜样。 (I'm sorry, I mistyped the format of the string.)
(对不起,我错误输入了字符串的格式。)
I'm doing my best to learn about regular expressions. 我正在尽力学习正则表达式。 But don't know enough yet to solve this problem.
但是还不知道还没有解决这个问题。
Here you go ( http://jsfiddle.net/VBmb8/ ): 你去( http://jsfiddle.net/VBmb8/ ):
function parse(str) {
var match = str.match(/(\w+)\s?([\w=]+)\s?\('(.+)'\)/);
return {
valueOne: match[1],
valueTwo: match[2],
arrayOfValues: match[3].split("','")
};
}
* After your edit * *编辑后*
http://jsfiddle.net/VBmb8/2/ http://jsfiddle.net/VBmb8/2/
function parse(str) {
var match = str.match(/(\w+)\s?([\w=]+)\s?\(?['"](.+)['"]\)?/);
return {
valueOne: match[1],
valueTwo: match[2],
arrayOfValues: match[3].split("','")
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.