Jarg7
Jarg7

Reputation: 1628

checking if a substring of length 5 is in another string (refactored)

I'm trying to check if string b contains any 5-character substring a.

This works, but is a little messy:

var a = "1eabcde";
var b = "12abcde12fg";

    for(var i=0; i<a.length; i++){
        for(var j=i;j<a.length-i;j++){
            if(a.charAt(j) == b.charAt(i) && a.charAt(j+1) == b.charAt(i+1) && a.charAt(j+2) == b.charAt(i+2) && a.charAt(j+3) == b.charAt(i+3) && a.charAt(j+4) == b.charAt(i+4)){
                alert("ya");
             }                              
         }
     }

Are there any other cleaner options?

Upvotes: 0

Views: 52

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234847

You can use substring and indexOf:

var a = "1eabcde";
var b = "12abcde12fg";

for (var i = 0; i <= a.length - 5; i++) {
    if (b.indexOf(a.substring(i, i + 5)) >= 0) {
        alert("ya");
    }
}

(You could use a.substr(i, 5) instead of a.substring(i, i + 5). Those two calls behave identically.)

Note that if you loop from 0 to a.length (as in your original code), then all suffixes of a of length 5 or less will be searched for in b.

In one respect, this code does not behave the same as your original: it will alert only once for each matching substring of a, regardless of how many times that particular substring may occur in b. Thus, if a = 'abcde' and b = '01abcde23abcde45, your original code would pop up two alerts (one for each occurrence of 'abcde'), whereas the above will only alert once. If you want the original behavior, change the if to a while like this:

for (var i = 0; i <= a.length - 5; i++) {
    var j = -1;
    while ((j = b.substring(j+1).indexOf(a.substr(i, 5))) >= 0) {
        alert("ya");
    }
}

Upvotes: 2

John Slegers
John Slegers

Reputation: 47101

This is the cleanest approach :

var a = "1eabcde";
var b = "12abcde12fg";

for (var i = 0; i <= a.length - 5; i++) {
    if(b.indexOf(a.substr(i, 5)) > -1) {
        alert("ya");
    }
}

Upvotes: 1

Related Questions