Reputation: 335
I have an attribute of HTML input element that has a value like this:
elements[1587f9aa-8a9e-4058-b1f3-d358041430c9][0][element-0][value]
How can I locate and get a number inside breckets [0] ?
This number will change as well as the left and right parts ot the string, so I can't just extract the 48-th (or whatever) symbol.
The pattern gonna be the same all the time, even [element-?][value]
part will be the same.
Upvotes: 0
Views: 51
Reputation: 455
Here is simple solution:
use jQuery to get string (all except number in brackets) and then replace it with empty char:
string.replace(/elements\[[^\]]+\]\[|\]\[element.*/g, "");
working example: http://regexr.com/3g1l3
Upvotes: 0
Reputation: 8685
Use a regular expression, like this:
/elements\[[^\]]+\]\[(\d+)\]/
This is like saying, "Find string elements[x][y]
, where x != ']'
and y is a number
"
You can then use the match
method on a string to capture the matches. Parentheses in a regular expression will capture a sub grouping of characters (such as y
in the above example).
Demonstration:
$('div').each(function(i,e){
var attr = $(e).attr('data-var');
var matches = attr.match(/elements\[[^\]]+\]\[(\d+)\]/);
console.log(matches[1])
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-var="elements[1587f9aa-8a9e-4058-b1f3-d358041430c9][0][element-0][value]"></div>
<div data-var="elements[1587f9aa-8a9e-4058-b1f3-d358041430c9][1][element-1][value]"></div>
Upvotes: 2
Reputation: 9988
Just split the string with ][
and get the element at position 1
var string = 'elements[1587f9aa-8a9e-4058-b1f3-d358041430c9][0][element-0][value]';
console.log(string.split('][')[1]);
Upvotes: 2