简体   繁体   中英

assign matched values from jquery regex match to string variable

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM