我做错了。我知道。
我想将正则表达式结果的匹配文本分配给字符串 var。
基本上,正则表达式应该提取两个冒号之间的任何内容
所以blah:xx:blahdeeblah 将导致 xx
var matchedString= $(current).match('[^.:]+):(.*?):([^.:]+');
alert(matchedString);
我希望将 xx 放入我的matchedString变量中。
我检查了 jquery 文档,他们说匹配应该返回一个数组。 (字符串字符数组?)
当我运行这个时,没有任何反应,控制台中没有错误,但我测试了正则表达式,它在 js 之外工作。我开始认为我只是做错了正则表达式,或者我完全不明白匹配函数是如何工作的
最佳答案
I checked the jquery docs and they say that match should return an array.
jQuery 不存在这样的方法。 match
是字符串的标准 javascript 方法。因此,使用您的示例,这可能是
var str = "blah:xx:blahdeeblah";
var matchedString = str.match(/([^.:]+):(.*?):([^.:]+)/);
alert(matchedString[2]);
// -> "xx"
但是,您实际上并不需要为此使用正则表达式。您可以使用另一种字符串方法 split()
使用分隔符将字符串划分为字符串数组:
var str = "blah:xx:blahdeeblah";
var matchedString = str.split(":"); // split on the : character
alert(matchedString[1]);
// -> "xx"
关于javascript - 将 jquery 正则表达式匹配中的匹配值分配给字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3101546/