I’m trying to figure out how to split a string using regex while having the results placed into a hash table.
Example:
var x = "Name: John Doe
Age: 30
Birth Date: 12/12/1981";
var arr = x.split(/Name:|Age:|Birth Date:/);
However while I can spit a string the problem is I can’t store the values into a useful format such as a hash etc. Since some of the information may not always be shown.
I would want the results to be something like:
var myHash = {}; // New object
myHash['Name'] = "John Doe";
myHash['Age'] = "30";
myHash['Birth Date'] = "12/12/1981";
Is there an easy why to do this?
Edit: The script is used to parse data from a generated report. And the format does not always have carriage returns. It’s going to be used to automatically generate notices instead of hand typing everything.
Example:
Name: John Doe Birth Date: 12/12/1981
Age: 30
However, after seeing examples I may be able to do it if I first add a carriage return or other special character in front of the regex matches. Need to figure out how to add a value in front of the regex matches first.
You can use two splits to first split it into items and then to split each item:
Working example: http://jsfiddle.net/jfriend00/kYwq6/
Depending upon exactly what you’re doing, you may want to trim the whitespace off beginning and end of each key and value before putting it into the results object.