2

I am doing it wrong. I know.

I want to assign the matched text that is the result of a regex to a string var.

basically the regex is supposed to pull out anything in between two colons

so blah:xx:blahdeeblah would result in xx

var matchedString= $(current).match('[^.:]+):(.*?):([^.:]+');
alert(matchedString);

I am looking to get this to put the xx in my matchedString variable.

I checked the jquery docs and they say that match should return an array. (string char array?)

When I run this nothing happens, No errors in the console but I tested the regex and it works outside of js. I am starting to think I am just doing the regex wrong or I am completely not getting how the match function works altogether

2
  • This looks like a syntax error - there is an unopened closing parenthesis in your regex as well as an unclosed opening parenthesis. Is your code displayed correctly? Commented Jun 23, 2010 at 12:31
  • 1
    The regex was wrong to begin with. [^.:]+:(.*?):[^.:]+ would have been correct. It was also even more wrong because my strings in reality were blah:blahblah:xx:blahdeeblah so it wouldn't have matched what I wanted. The split function did the trick. Commented Jun 23, 2010 at 13:38

1 Answer 1

6

I checked the jquery docs and they say that match should return an array.

No such method exists for jQuery. match is a standard javascript method of a string. So using your example, this might be

var str = "blah:xx:blahdeeblah";
var matchedString = str.match(/([^.:]+):(.*?):([^.:]+)/);
alert(matchedString[2]);
// -> "xx"

However, you really don't need a regular expression for this. You can use another string method, split() to divide the string into an array of strings using a separator:

var str = "blah:xx:blahdeeblah";
var matchedString = str.split(":");  // split on the : character
alert(matchedString[1]);
// -> "xx"
Sign up to request clarification or add additional context in comments.

1 Comment

Even better. Thanks Andy! Now I fully understand split

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.