1

function match(str1, str2) {
  var matched = false
  for (i in str1) {
    if (str1[i] == str2[0]) {
      for (j in str2) {
        if (str2[j] != str1[i]) {
          return false
        } else {
          i++
          matched = true
        }
      }

    }
    return matched
  }

}

console.log(match("umbrella", "rella"))

Can someone fix this code. Is this piece of code good enough. or any improvements. I wanted to find a string in another string with just using the for loops. I saw some answers but they were too complex.

Im a beginner

3 Answers 3

2

You are returning after only one iteration, change

    }
    return matched
  }
}

to

    }
  }
  return matched
}

That being said, if I'm understanding your code correctly, right now it will fail if it starts to find a match, but then it doesn't match, and there is a match later.

E.g.

console.log(match("umbrerella", "rella"))

function match(str1, str2) {
  var matched = false
top:
  for (i in str1) {
    if (str1[i] == str2[0]) {
      for (j in str2) {
        if (str2[j] != str1[i]) {
          matched = false
          continue top
        } else {
          i++
          matched = true
        }
      }
      if (matched) return true;

    }
  }
  return matched
}

console.log(match("umbrella", "rella"))
console.log(match("umbrella", "della"))
console.log(match("umbrerellas", "rella"))

0
2

The for ... in statement iterates over the own enumerable keys of the object. This could be handy for objects, but it does not work always for arrays (Why is using "for...in" for array iteration a bad idea?).

Instead use a classic for statement with an index variable from zero to less than the length.


You could take some short circuits and exit early on found and omit iterating over the lengths.

function match(str1, str2) {
    for (let i = 0, l = str1.length - str2.length + 1; i < l; i++) {
        let match = true;
        for (let j = 0; match && j < str2.length; j++) {
            if (str1[i + j] !== str2[j]) match = false;
        }
        if (match) return true;
    }
    return false;
}

console.log(match("umbrella", "rella"));
console.log(match("umbrella", "rello"));

-1

Why don't you just use:

console.log("umbrella".includes("rella"))

2
  • I dont want to use any helper methods
    – potnine
    Commented May 21, 2021 at 21:21
  • The OP only wants to use for loops.
    – code
    Commented May 21, 2021 at 21:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.