Reputation: 1578
I'd like to search only a specific piece of a string and show it using nothing more than JS or Jquery.
For example, (It just looks like a JSON, but it's not, it's just brackets some stuff ;) ):
var data =
[{"name":"node1","id":1,"is_open":true,"children":
[
{"name":"child2","id":3},
{"name":"child1","id":2}
]
}];
I'd like to pick up only the ID numbers:
The "code" below is not a language, it's just an example to help understanding what I'd like to do on JS/jQuery
var IDs = [searchThrough] data [where there is] "id": [getContent] after : and before , or } alert("IDs: "+IDs);
It allows me to:
1 - set a parameter of what I want from a string find "id":
on data
.
2 - set the start and end for getting the content after : and before , or }
How can I do it?
Thanks in advance.
"Beam me up Scotty!"
Upvotes: 0
Views: 62
Reputation: 314
If we take the assumption that you are dealing with a string, we can pull out the data using regular expression:
var str = '[{"name":"node1","id":1,"is_open":true,"children":\n [\n {"name":"child2","id":3},\n {"name":"child1","id":2}\n ]\n }];';
var regex = /"id":([0-9]*)/g;
var match = regex.exec(str);
var res = new Array();
while (match != null) {
res.push(match[1]);
match = regex.exec(str);
}
var ids = res.join();
alert("IDs: " + ids);
This demo will give you an alert box with the content "IDs: 1,3,2"
Upvotes: 1
Reputation: 1946
I am no regex guru,but this is my try.
var data = '[{"name":"node1","id":1,"is_open":true,"children":[{"name":"child2","id":3},{"name":"child1","id":2}]}]';
var arrays=[];
var t1=data.match(/"id":[0-9]+(,|})*/g);
for(var x=0;x<t1.length;x++)
{
arrays.push(t1[x].match(/\d+/));
}
alert(arrays);
Upvotes: 1
Reputation: 1152
If I understand you, you want to search a String that represents the data. In this case, you could use a regular expression like the following:
var matcher = /"id":([^,\}]*/g, // capture all characters between "id" and , or }
match, IDs = [];
while (match = matcher.exec(data)) {
IDs.push(match[1]);
}
alert(IDs);
Upvotes: 1