Vaibhav Pachauri Vaibhav Pachauri - 26 days ago 14
Javascript Question

Check if string contains substring without using any standard JavaScript methods?

So I need to implement a javascript method which will return true or false depending on if the masterString contains a subString.

I did something like following but not sure if this is the right approach :

function contains(masterString, subString) {
if(subString.length > masterString.length){
return false;
}
for(var i=subString.length-1; i<masterString.length; i++){
if(concatString(i - subString.length-1, i, masterString) === subString){
return true;
}
}
return false;

}

function concatString(index1, index2, string){
var conString = '';
console.log(index1, index2-1, string);
for(var i=index1; i<index2-1; i++){
conString += string[i];
}
console.log(conString);
return conString;
}


contains('abcd', 'bc');


It isn't working fine though.

Can we implement it? Thanks :)

Answer

You have a good solution. But I think mine is easier.

By the way: I think .length is a javascript funciton too.

function length(string){
  var count = 0;
  while(string[count] != undefined)
     count++;
  return count;
}

function contains(masterString, subString) {
    var masterStringLength = length(masterString);
    var subStringLength = length(subString);
    for(var i = 0; i <= masterStringLength - subStringLength; i++)
    {
        var count = 0;
        for(var k = 0; k < subStringLength; k++)
        {
            if(masterString[i + k] == subString[k])
               count++;
            else
               break;
        }
        if(count == subStringLength)
            return true;

    }
    return false;
}

console.log(contains('abcdefgh', 'bcde'));
console.log(contains('abcdefgh', 'ab'));
console.log(contains('abcdefgh', 'fgh'));

Comments