2

I have a string:

services[custom][mainData]

How can I get the string mainData?

I have tried:

var result = id.match('\[(.*?)\]'); alert(result[1]); var result = id.match(\[(.*?)\]); alert(result[1]); 

To no avail. its simple for me to do with one set of brackets, the 2nd set is what throws me off.

2
  • Are the strings always in that format? Commented Jun 28, 2016 at 14:04
  • If it's always the last you want, simply /\[([^\]]*)\]$/ should do it for you. Commented Jun 28, 2016 at 14:24

5 Answers 5

2

You can use a greedy .* before matching [ and ] to make sure you are always matching last [...]:

var str = 'services[custom][mainData]'; var result = str.match(/.*\[([^\]\[]*)\]/)[1]; console.log(result); //mainData

RegEx Demo

Sign up to request clarification or add additional context in comments.

Comments

2

If the strings are always in that format, you wouldn't really need a complicated regex, you can just split on the ][ and take the remaining string without the last ]. Something like:

id.split('][').pop().slice(0, -1); 

Here's the code with comments for each step:

var id = 'services[custom][mainData]'; var result = id.split('][') // split on `][` gives [ 'services[custom', 'mainData]' ] .pop() // take the last match gives 'mainData]' .slice(0, -1); // trim the last char gives 'mainData' console.log(result); // logs 'mainData'

Comments

0

This regex should do it for you, as long as you catch the right group!

Comments

0

When you want to extract the second pair of brackets, just match the first pair of brackets as well.

var result = id.match(/\[(.*?)\]\[(.*?)\]/); 

With your example of id being services[custom][mainData], result[1] will now be custom and result[2] will be mainData.

Comments

0

This works:

var test = "services[custom][mainData]"; var re = /\[(\w+)\]\[(\w+)\]/g; var res = re.exec(test); document.write(res[2]); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.