Andrew
Andrew

Reputation: 747

Using for loop to find specific characters in string

I am attempting the bean counting example in the functions chapter of the book Eloquent Javascript. My function is returning a blank.

Without giving me the full answer (I'm working through this example to learn), can someone tell me why my code is not printing any text?"

var string = "donkey puke on me boot thar be thar be!";

for (var i = 0; i <= string.length; i++);

function getB(){
  if (string.charAt(i) == "b")
    return i;
  else return "";
}

console.log(getB());

Upvotes: 1

Views: 12844

Answers (6)

Tune389
Tune389

Reputation: 91

another example: collect all b positions:

var string = "donkey puke on me boot thar be thar be!";

function getB(string){
    var placesOfB = [];
    for (var i = 0; i < string.length; i++) {
        if (string.charAt(i) == "b") {
            placesOfB.push(i);
        }
    }
    return placesOfB;
}

console.log(getB(string));

Upvotes: 1

Raphael M&#252;ller
Raphael M&#252;ller

Reputation: 2200

if you want to print every position your value is at, you can program something like this:

var string = "donkey puke on me boot thar be thar be!";

for (var i = 0; i <= string.length; i++)
{
   getChar(i, "b");
}

function getChar(i, input)
{
    if (string.charAt(i) == input)
        console.log(i);
}

Upvotes: 1

Cosmin
Cosmin

Reputation: 2214

There is something wrong about how you're trying to implement this feature. First of all I think it's better if you have a function that accepts the string and the char as parameters in order to call it whenever you want.

Example of calling :

getChar('this is my custom string', 'c')  -> it should search character `c` in `this is my custom string`

getChar('this is another custom string', 'b')  -> it should search character `b` in `this is another custom string`

Example of implementation :

var getChar = function(string, char){
  for(var i=0;i<string.length;i++)
  {
    if(string.charAt(i)==char) console.log(i);
  }
}

Now, try to make it not case-sensitive and instead of console.log the output try to return a sorted array with character positions

Upvotes: 2

BabyDuck
BabyDuck

Reputation: 1249

Use This,

var string = "donkey puke on me boot thar be thar be!";

for (var i = 0; i <= string.length; i++) {
  if (string.charAt(i) == "b") {
    console.log(i);
  }
}

Upvotes: 1

codeepic
codeepic

Reputation: 4102

Without giving you the full answer, I'll just give you pointers: 1. Your for loop is not complete - it doesn't do anything. 2. Your getB() function needs to accept string parameter in order to perform some action on it. 3. The if..else statement doesn't have opening and closing brackets {}

Upvotes: 0

Lu&#237;s Soares
Lu&#237;s Soares

Reputation: 6203

tip: your for has no body (putting ; after it just loops without doing anything)... and it does not make sense to define a function inside that for.

Upvotes: 0

Related Questions