0

i want to match pattern on the string using for loop and i create code like this :

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')); // ["abc","abc"]

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

but on second case, it resulted like this :

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

the question is it possible to put cHg to the array by ignoring case sensivity without using regex?

thanks before.

1
  • 1
    Use toLowerCase() on both sides of ===. Commented Dec 28, 2019 at 2:46

2 Answers 2

1

Yes and you can use substring to make the code simpler:

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Convert to lowercase before comparing.

You can also use substr() instead of concatenating specific indexes of the string. This allows you to work with any size partial.

And you should push the substring onto the result array, not partial, so that you get the case from the string.

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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.