3

I'm trying to do a little logo guessing game. I have an array of logo names and then you have to guess which logo name it is.

I have removed the whitespaces from the logo names using the code below.

var cleanLogoName = randomLogoName.replace(/ /g,'');

Then I want to know the amount of characters in the logo name by using this code.

var numberOfChar = cleanLogoName.length;

The game however is a hangman game, so I won't need to count the same characters more than once.

For example:

Coca cola

I would only need to count the the c, a, o one time and not two times.

Is there anyway to do this with javaScript?

  • In your hangman game logic you surely have a list of single characters. Can't you just count that? Please show us your code. – Bergi Aug 15 '13 at 12:37
  • 1
    Split your string to an array and then use something like this: http://stackoverflow.com/questions/1960473/unique-values-in-an-array – Alma Do Aug 15 '13 at 12:38
  • I need to know the total of characters without duplicates to find out when someone has guessed the word. – user2559792 Aug 15 '13 at 12:41
  • Thanks Alma Do Mundo, that looks like something I can use. – user2559792 Aug 15 '13 at 12:42

2 Answers2

4

You can use a regex to detect and remove characters that appear multiple times:

"coca cola".replace(/\s|(.)(?=.*\1)/g, "").length // 4

(using a backreference to a captured letter in a lookahead expression)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

I think some pseudo code will help you understand the concept a little better, and encourage you to solve the problem yourself. And this offers a regex free solution, should you want it.

Define an empty list of characters.
Define a variable, count = 0;

for every letter in your word
    if(list does not contain this letter)
        count = count + 1
        list.add(count)
christopher
  • 26,815
  • 5
  • 55
  • 89