Search code examples
actionscript-3textfieldsettext

Applying setTextFormat to textField more than once in AS3


I'm writing a program where entered text is compared to an original (for memorization help).

Whenever a letter is wrong, I want the letter to turn red. However, when I loop it to set the textField for the wrong letters:

function checkAgainstBible(inputText:String):void
{
    var outputTextL:String = ""
    for(var n:Number = 0; n < inputText.length; n++)
    {
    var inputTextL:String = inputText
    var specLetter:String = inputTextL.charAt(n);

        if(inputText.charAt(n) != bibleVerse.charAt(n))
        {
            outputTextL = outputTextL + specLetter
            outputText.text = outputTextL;
            outputText.setTextFormat(red, n, n+1);
        }
        else
        {
            outputTextL = outputTextL + specLetter
            outputText.text = outputTextL;
            outputText.setTextFormat(green, n, n+1);
        }

}

It overwrites the old one, making it so only the last letter is formatted. How do I avoid this?

EDIT I could use HTML text, but I would like to re-insert spaces afterwards, and I couldn't do that with the extra text HTML text adds to the string specLetter. /EDIT


Solution

  • You can set the whole text first, then set the textformat

    function checkAgainstBible(inputText:String):void
    {
         outputText.text = inputText;
    
        for(var n:Number = 0; n < inputText.length; n++)
        {
            var inputTextL:String = inputText;
            var specLetter:String = inputTextL.charAt(n);
    
            if(inputText.charAt(n) != bibleVerse.charAt(n))
            {
                outputText.setTextFormat(red, n, n+1);
            }
            else
            {
                outputText.setTextFormat(green, n, n+1);
            }
    
        }
    }