J Akhtar
J Akhtar

Reputation: 667

Javascript not producing the output required

I want to find the value of str variable inside text variable and store the occurrences in the hits array. I have tried so many times, but with no luck getting this program to work:

/*jshint multistr:true */

text = "tang sit men loop";
var str = "men";
var hits = [];

for( var i = 0; i < text.length; i++ ) {
    if( text[i] === "m") {
        for( var j = i; j < (str.length + 1); j++ ) {
            hits.push( text[i] );
        }
    }
}

if( hits.length === 0 ) {
    console.log( "Not found" );
}
else {
    console.log( hits );
}

Upvotes: 0

Views: 55

Answers (3)

MagJS
MagJS

Reputation: 422

you were just missing one thing in your inner for loop, the j vs the i:

  1. use hits.push( text[j] ); vs. hits.push( text[i] );

JS:

var text = "tang sit men loop";
var str = "men";
var hits = [];

for( var i = 0; i < text.length; i++ ) {
    if( text[i] === "m") {

        for( var j = i; j < (str.length + i); j++ ) {
            hits.push( text[j] );
        }
    }
}

if( hits.length === 0 ) {
    console.log( "Not found" );
}
else {
    console.log( hits );
}

Here is the link to the working example: http://jsbin.com/gaxenidalo/edit?js,console

Hope that helps!

Upvotes: 0

yeppe
yeppe

Reputation: 689

I could reform the code to this extend but please check your below condtion for the for loop--> This condition is faulty for( var j = i; j < (str.length + 1); j++ ) {

function testingThisOneHere(){
var text = "tang sit men loop";
var str = "men";
var hits = [];
alert("text.length"+text.length);
alert("str.length"+str.length);
for( var i = 0; i < text.length; i++ ) {
    //alert("condition: "+(text[i] == "m"));
    //alert("text[i]"+text[i]);
    if( text[i] == "m") {



        for( var j = i; j < (str.length + 1); j++ ) {

            hits.push( text[i] );
        }
    }
}

if( hits.length != 0 ) {

    alert( hits );
}
else {
    alert( "Not found" );
}
}

Upvotes: 0

Hamed
Hamed

Reputation: 1213

You have two mistakes in your nested for loop. Try the following:

    for( var j = i; j < (i + str.length + 1); j++ ) {
        hits.push( text[j] );
    }

First, you should change j < (str.length + 1) to j < (i + str.length + 1). Then you should change hits.push( text[i] ); to hits.push( text[j] );

Following these corrections, the output looks like: m,e,n,

On point to mention, you can simply use JSFiddle to debug your code.

Upvotes: 1

Related Questions