husslela03 Posted April 19, 2010 Share Posted April 19, 2010 Hello: I would like to display the first character of a word: like this: c _ _ _ _ and then all the rest is underline spaces i created this function but i do not know how to add in the theWord.charAt(0). I tried this: pattern += theWord.charAt(0) + " _ "; but i got this c _ c _ c _ .... which is not what i want function displayPattern(theWord) { var pattern= " "; for(i=0; i<theWord.length; i++) { if(theWord.charAt(i)==" ") { pattern += " "; } else pattern += " _ "; } document.myLingo.toGuess.value=pattern; Any help would be appreciated. Quote Link to comment Share on other sites More sharing options...
ignace Posted April 19, 2010 Share Posted April 19, 2010 function getMask(theWord) { return theWord.toUpperCase().replace(/[A-Z]/, "_"); } function revealMask(theWord, wordMask, letter) { if (!letter) return theWord; var length = theWord.length; for (var i = 0; i < length; ++i) { if (theWord.charAt(i) == letter) { wordMask[i] = letter; } } return wordMask; } Don't use " _ " use CSS instead (letter-spacing) and use a monospaced font. It's funny you create something like this as I have created the same thing but used PHP instead you can have a look at: http://www.mediafire.com/file/wetmhyguem3/hangman.zip I use it mainly for my own pleasure and I don't recommend using it in any production environment Quote Link to comment Share on other sites More sharing options...
salathe Posted April 19, 2010 Share Posted April 19, 2010 "hello world".replace(/(?!^)\w/g, "_") gives us h___ _____ Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 19, 2010 Share Posted April 19, 2010 Damn, salathe beat me to it. Ah well, here is a working example: <html> <head> <script type="text/javascript"> function displayPattern(theWord) { var pattern = theWord.replace(/(?!^)\w/g, "_") document.getElementById('pattern').innerHTML = pattern; return; } </script> </head> <body> Select a phrase:<br /> <select onchange="displayPattern(this.options[this.selectedIndex].value)"> <option value="">-- Select One --</option> <option value="The First Option">The First Option</option> <option value="Another Option">Another Option</option> <option value="Last Option">Last Option</option> </select> <br /><br /><br /> Pattern:<br /> <div id="pattern" style="letter-spacing:6px"></div> </body> </html> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.