Daniel Morgan
Daniel Morgan

Reputation: 561

How to check if there is no specific character left

I'm creating a JavaScript game of Hangman (JavaScript only NO jQuery whatsoever) this is my code to replace all unguessed letters with an '_'

function partialWords(random_word, letters) {
    var returnLetter = "";
    for (i = 0; i < random_word.length; i++) {
        if (letters.indexOf(random_word[i]) !== -1) {
            returnLetter = returnLetter + random_word[i];
        } else {
            returnLetter = returnLetter + ' _ ';
        }
    }
    return returnLetter;
}

I was just wondering if anyone would be able to help me with figuring out how to check if there are no more '_' left, thanks in advance!

Upvotes: 0

Views: 59

Answers (2)

David Thomas
David Thomas

Reputation: 253318

To find out if there are any _ in a given string:

if (stringVariableToCheck.indexOf('_') !== -1) {
    // there's at least one '_' in the string
}

To find out how many _ there are in that string:

var numOfUnderScores = stringVariableToCheck.replace(/[^_]/g,'').length;

A somewhat contrived JS Fiddle demo (the demo does require an up-to-date browser, though).

Upvotes: 2

Atif
Atif

Reputation: 10880

There is an indexOf method for a String Object too

if(returnLetter.indexOf('_') == -1) {

}

You can also hold missed letters in a separate Array

function partialWords(random_word, letters) {
    var returnLetter = "";
    var missedLetters = [];
    for (i = 0; i < random_word.length; i++) {
        if (letters.indexOf(random_word[i]) !== -1) {
            returnLetter = returnLetter + random_word[i];
        } else {
            returnLetter = returnLetter + ' _ ';
            missedLetters.push(random_word[i]);
        }
    }

    if(missedLetters.length > 0) {
        // do something
        // send missed letters
        return missedLetters.join(', ');
    }
    return returnLetter;
}

Upvotes: 1

Related Questions