1

How to detect if string contains pattern with JavaScript:

1. input="[Lorem]foo";
2. input="[ ]";
3. input="[ipsum]foo";
4. input="[dolor]foo1";
5. input="[sit  ]foo2";
6. input="[ amet]foo3";
7. input="amet]foo3";
...

Script should process input in this way:

1. string1='Lorem'; string2="foo";
2. do nothing;
3. string1='ipsum'; string2="foo";
4. string1='dolor'; string2="foo1";
5. do nothing;
6. do nothing;
7. do nothing;
...

This would be a part of script...

input  = "[asd]qwe";
input2 = "qwe";

processit(input);
processit(input2);

function processit(e){

   if(..???..){
      alert(string1);
      alert(string2);
   }
   else {
      return false;
   }

}

Thank you for your time.


EDIT: Solution must be cross-browser

IE7 +

Firefox 3.6+

Chrome 7+ ...

1
  • Kind of a hard to see what seems to be the problem! If you need info about Regular expression - MDN RegEx and a site dedicated to RegEx Commented Apr 8, 2012 at 2:34

3 Answers 3

4
+50

jsbin code

This regex should achieve the result: /\[([a-zA-Z0-9]+)\]([a-zA-Z0-9]+)/

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

2 Comments

Those [^\s] constructs shouldn't be there. You're already telling it to match alphanumerics and nothing else with [a-zA-Z0-9]+; there's no need to tell it not to match whitespace. Also, you're requiring the first string to be at least three characters long, and you're dropping the last character because the second [^\s] is outside the capturing group.
\w will work in place of each [a-zA-Z0-9] - it is equivalent to [a-zA-Z0-9_]. Also, as you want to match only the whole string, the regex should start with ^ and end with $.
1

You can take advantage of how split() works with capturing groups.

var pieces = str.split(/\[(\w+?)\]/);

You may get some empty string values. You can remove them with...

pieces.filter(function(piece) { return piece; });

jsFiddle.

4 Comments

It DOES NOT work in Internet Explorer. Webpage error details Message: Object doesn't support this property or method Any suggestions?
@enloz You can shim split() to get it to work in IE.
I would imagine that pieces.filter is the piece unsupported by IE.
@EricWendelin: filter is unsupported in IE <= 8. IE 9 does support it.
0

Your actual requirements are unclear, so I'm guessing. The following will allow only non-empty alphanumeric-plus-underscore-only strings inside and after the brackets, and tries to match the whole string rather than multiple occurrences in a longer string.

var input = "[Lorem]foo";
var string1, string2;
var result = /^\[(\w+)\](\w+)$/i.exec(input);
if (result) {
    string1 = result[1];
    string2 = result[2];
}
alert(string1 + ", " + string2);

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.