0

I have a problem that is kind of difficult to explain.

What I would like to do is look in a string of text, for example "hello". And each character in this string should be compared to user input, one by one.

If the text starts as full red, user presses "H" then the "h" letter of "hello" turns green, and the rest of the letters remain red.

How could I do this with javascript? Could anyone point me in the right direction please?

2
  • Are you using a library such as jQuery or mooTools? Commented Mar 26, 2012 at 16:25
  • prefere not to include libraries, but if they provide a beautifully simple method I'm all ears. Commented Mar 26, 2012 at 16:36

2 Answers 2

2
var name = "Josh";

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

  alert( name.charAt(i) );

}
Sign up to request clarification or add additional context in comments.

1 Comment

how could I separate the fillStyle of the characters?
1

In general, you will need the .charAt method from String.prototype. Example:

var str       = "Hello world",
    userInput = "Helli world";

for(var i = 0, len = str.length; i < len; i++) {
    console.log( 'character at pos ', i, ' is: ', str.charAt( i ) === userInput.charAt( i ) );
}

Most browser also allow you to access characters using the bracket notation str[i] for instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.