Reputation: 854
I have some strings separated with comma. Those value I need to get in an array. Which I am able to do. For getting this I had done this.
var productArray = $("#service").data('product').split(',');
And those data are showing properly in productArray
variable. Those data format are like this.
["[44]Medicine 2", "[63]Test Sam "]
Now I need to get those number which is inside this character []
. For instance I need to get 44
and 63
as per above data given.
I had done nothing for this part as I am not getting any way.
Upvotes: 1
Views: 51
Reputation: 28611
You can use array.map to convert your existing array.
Here's an example using .split
on [
and ]
to break into parts. Another viable solution would be to use a regex.
// from #service.data()
var data = "[44]Medicine 2,[63]Test Sam";
var array = data.split(",");
var ids = array.map(s => s.split("]")[0].split("[")[1]);
console.log(ids)
var id_name = array.map((s) => {
return { id : s.split("]")[0].split("[")[1], name : s.split("]")[1] };
});
console.log(id_name)
As an alternative, if you can change how the data-
attribute is generated, you can store (valid) json directly in the html then jquery's .data()
will give you an object so there's no additional parsing required:
var data = $("#data").data("data");
console.log(data.length, data[0].id, data[0].name);
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='data' data-data='[{"id":"1","name":"test"},{"id":"2","name":"2nd"}]'></div>
Upvotes: 1
Reputation: 7303
You could use RegEx for that: /\[(.*)\]/
let res = ["[44]Medicine 2", "[63]Test Sam "].map(e => Number(e.match(/\[(.*)\]/).pop()));
console.log(res);
Or as one-step solution with your code:
var productArray = $("#service")
.data('product')
.split(',')
.map(e => Number(e.match(/\[(.*)\]/).pop()));
Note: I also implicitly casted to Number
.
Upvotes: 1
Reputation: 5828
Try using a regular expression:
//instead of splitting the string:
console.log("[44]Medicine 2,[63]Test Sam ".match(/(?<=\[)\d+(?=\])/g));
Upvotes: 1