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 pletely not getting how the match function works altogether
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 pletely not getting how the match function works altogether
Share Improve this question edited Jun 23, 2010 at 12:36 Andy E 345k86 gold badges481 silver badges451 bronze badges asked Jun 23, 2010 at 12:27 branchgabrielbranchgabriel 4,2514 gold badges36 silver badges49 bronze badges 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? – Tim Pietzcker 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. – branchgabriel Commented Jun 23, 2010 at 13:38
1 Answer
Reset to default 6I 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"
- String.match
- String.split