简体   繁体   English

使用不带正则表达式的循环匹配字符串上的模式

[英]matching pattern on the string using loop without regex

i want to match pattern on the string using for loop and i create code like this :我想使用 for 循环匹配字符串上的模式,我创建这样的代码:

function partialCheck(str, partial) {
  
  var pattern = [];
  for (var i =0; i <= str.length; i++){
    if(partial === str[i]+str[i+1]+str[i+2]){
      pattern.push(partial);
    }
  }
  return pattern;
}

on the test case, it should show the result like this :在测试用例中,它应该显示如下结果:

console.log(partialCheck('abcdcabdabc', 'abc')); console.log(partialCheck('abcdcabdabc', 'abc')); // ["abc","abc"] // ["abc","abc"]

console.log(partialCheck('accHghebchg', 'chg')); console.log(partialCheck('accHghebchg', 'chg')); // ["cHg","chg"] // ["chg","chg"]

but on second case, it resulted like this :但在第二种情况下,结果是这样的:

console.log(partialCheck('accHghebchg', 'chg')); console.log(partialCheck('accHghebchg', 'chg')); // ["chg"] // ["chg"]

the question is it possible to put cHg to the array by ignoring case sensivity without using regex?问题是否可以通过忽略大小写敏感度而不使用正则表达式将 cHg 放入数组?

thanks before.之前谢谢。

Convert to lowercase before comparing.比较前转换为小写。

You can also use substr() instead of concatenating specific indexes of the string.您还可以使用substr()而不是连接字符串的特定索引。 This allows you to work with any size partial .这允许您使用任何大小的partial

And you should push the substring onto the result array, not partial , so that you get the case from the string.并且您应该将子字符串推送到结果数组,而不是partial ,以便您从字符串中获取大小写。

 function partialCheck(str, partial) { var pattern = []; partial = partial.toLowerCase(); for (var i = 0; i <= str.length - partial.length; i++) { if (partial === str.substr(i, partial.length).toLowerCase()) { pattern.push(str.substr(i, partial.length)); } } return pattern; } console.log(partialCheck('accHghebchg', 'chg'));

Yes and you can use substring to make the code simpler:是的,您可以使用substring使代码更简单:

function partialCheck(str, partial) {

  var pattern = [];
  partial = partial.toLowerCase();
  for (var i =0; i <= str.length; i++){
    var substr = str.substring(i, i + 3);
    if(partial === substr.toLowerCase()){
      pattern.push(substr);
    }
  }
  return pattern;
}

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

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