繁体   English   中英

在match的正则表达式上指示的Javascript match()字符串字母

[英]Javascript match() string letters which are indicated on regular expression of match

我有一个包含字符串的变量,我只想返回正则表达式中的字母(“ b” “ D”)或我从match()返回的正则表达式中指示的任何字母。

var kk = "AaBbCcDd".match(/b|D/g); 
     kk.forEach(function(value,index){
     console.log(value,index) 
});

我的问题是我认为正则表达式是因为返回b和D,但索引不是kk变量的索引,所以我不确定,为什么...所以有人可以帮助我,因为我被卡住了

javascript中的match方法仅返回具有给定匹配项的数组: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match

您将需要实现一个新函数,该函数将遍历字符串的所有字符并返回给定的匹配索引。 此方法可以使用String.prototype中的函数searchhttps : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/search

您必须编写一个新函数来获取匹配的正则表达式的索引,例如以下示例:

var re = /bar/g,
  str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
  alert("match found at " + match.index);
}

希望这个能对您有所帮助

其实这就是答案:

var kk = "AaBbCcDd".match(/B?d?/g); 
     kk.forEach(function(value,index){
     console.log(value,index) 
});

如果有人会遇到这种情况...

match()正则表达式B?d? 将返回一个数组,该数组指示初始数组kk的"B""d"的位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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