Reputation: 39
I would like to capture the array key from a string.
Here are my words: message[0][generic][0][elements][0][default_action][url]...
I want to capture the array keys after message[0][generic][0][elements][0]
, and the expected results are default_action
and url
etc.
I have tried following patterns but not work.
message\[0\]\[generic\]\[0\]\[elements\]\[0\](?=\[(\w+)\])
: it captures default_action
only;\[(\w+)\]
: it captures all array keys, but includes 0
, generic
, elements
...Is there any regex pattern for JavaScript that make the result array inverse, like [url, default_action]
?
Upvotes: 0
Views: 125
Reputation: 15461
To extract any number of keys and reverse the order of the elements in resulting array:
str = "message[0][generic][0][elements][0][default_action][url]";
res = str.match(/\[([^\d\]]+)\](?=\[[^\d\]]*\]|$)/g)
.map(function(s) { return s.replace(/[\[\]]/g, "") })
.reverse();
console.log(res);
Upvotes: 0
Reputation: 1816
You can replace unwanted part of a string,and then get all other keys.
var string = 'message[0][generic][0][elements][0][default_action][url][imthird]';
var regexp = /message\[0\]\[generic\]\[0\]\[elements\]\[0\]/
var answer = string.replace(regexp,'').match(/[^\[\]]+/g)
console.log(answer);
Upvotes: 1
Reputation: 92854
The solution using String.prototype.split()
and Array.prototype.slice()
functions:
var s = 'message[0][generic][0][elements][0][default_action][url]...',
result = s.split(/\]\[|[\[\]]/g).slice(-3,-1);
console.log(result);
Upvotes: 0