Question

I've been struggling with this problem for a while:

I have a string containing HTML and I'm using a regular expression to get the characters between the tags. I'm then attempting to apply a TextFormat to those characters.

The problem is that I'm using the TextField's "htmlText" property instead of it's "text" property (because I don't want the HTML tags to be visible). So, the character index that's returned from the regular expression is incorrect, when I apply the TextFormat.

Here is some sample code which illustrates the problem:

var txt:String = "<b>Sample</b> string with bold text";

var tf:TextField = new TextField();
addChild(tf);
tf.htmlText = txt;

var format:TextFormat = new TextFormat();
format.bold = true;

var regExp:RegExp = /<b>(.*?)<\/b>/g;
var match:Object = regExp.exec(txt);
while (match != null) {
    tf.setTextFormat(format, match.index, match.index + match[0].length);
    match = regExp.exec(txt);
}

This gives me:

"Sample string with bold text"

instead of the desired:

"Sample string with bold text"

because match[0].length is seven characters too long, due to the HTML tags <b></b>.

What can I do about this? Thanks!

Was it helpful?

Solution

Using TextField.htmlText, <b> tags should give bold text, without any need for TextFormat.bold or regexp, provided you embed the right fonts (or use device fonts).

But, I know there is sometimes issues with the HTML support in TextFields in combination with font handling, and perhaps your actual situation is more complex than the example with bold text. In that case I would recommend using StyleSheet formatting instead of the regexp/TextFormat combo. Besides the problem with offset mismatch that you have encountered, I believe that combining the two different approaches to text formatting - HTML and TextFormat - runs the risk of giving other problems, while using HTML text and StyleSheet are meant to be used together.

I started writing an example of using StyleSheet/htmlText, but since <b> should work anyway, without styling, it got a bit weird, so I scratched it. But let me know if you need example code.

OTHER TIPS

tf.setTextFormat(format, match.index, match.index + match[1].length); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top