1

I have the String "Edit[user]", but I need get "Edit" and later "user".

How can I do it? Any help would be useful.

Of course I need do it with JavaScript regex.

4
  • This is a fairly basic regex - check out regular-expressions.info/quickstart.html for getting started with regular expressions. Commented Apr 11, 2013 at 15:09
  • are you saying you need to do it with a regexp because that's a requirement, or because you don't know any other way to go about it? Commented Apr 11, 2013 at 15:09
  • What exactly is allowed between the brackets? Only letters? Whitespace? Any other characters? Commented Apr 11, 2013 at 15:11
  • have you tried word separator \b? Commented Apr 11, 2013 at 15:25

2 Answers 2

4
var regex = /(.+)\[(.+)\]/;
var str = "Edit[user]";
regex.exec(str); // will return ["Edit[user]", "Edit", "user"]

Or you could do it this way with the String#split method:

var str = "Edit[user]";
str.split(/\[(.+)\]/); // will return ["Edit", "user"]
Sign up to request clarification or add additional context in comments.

Comments

0

What you are looking for is grouping. I'll quickly explain how these work in JavaScript and leave the actual Regular Expression up to you.

var myString = "cat dog frog";
var myRegexp = /(cat).*(frog)/g;
var match = myRegexp.exec(myString);

match will be an array, index 0 will have the whole match, and any others will have the contents of the groups.

match[0] = "cat dog frog"
match[1] = "cat"
match[2] = "frog"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.