简体   繁体   English

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

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

I have a variable which contain a string and I want to return only the letters from regular expression (“b” and “D”) or any letter that I indicate on regular expression from match(). 我有一个包含字符串的变量,我只想返回正则表达式中的字母(“ b” “ D”)或我从match()返回的正则表达式中指示的任何字母。

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

My problem is that regular expression I think because is returning b and D but the index is not the index from kk variable and I'm not really sure, why ... so if someone can help me a little bit because I stuck 我的问题是我认为正则表达式是因为返回b和D,但索引不是kk变量的索引,所以我不确定,为什么...所以有人可以帮助我,因为我被卡住了

The match method from javascript only returns an array with the given match: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match javascript中的match方法仅返回具有给定匹配项的数组: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match

You would need to implement a new function which will loop through all characters of your string and return the given index of the matches. 您将需要实现一个新函数,该函数将遍历字符串的所有字符并返回给定的匹配索引。 This method could use the function search from String.prototype: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/search 此方法可以使用String.prototype中的函数searchhttps : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/search

You have to write a new function to get the index of the matched regex like a sample below:- 您必须编写一个新函数来获取匹配的正则表达式的索引,例如以下示例:

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

Hope this will help you 希望这个能对您有所帮助

Actually this is the answer : 其实这就是答案:

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

if someone will encounter this scenario ... 如果有人会遇到这种情况...

The match() regular expresion B?d? match()正则表达式B?d? will return an array indicating the position of "B" and "d" of the initial array kk. 将返回一个数组,该数组指示初始数组kk的"B""d"的位置。

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

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