Mike Lowery
Mike Lowery

Reputation: 2868

Html.fromHTML removes double space

Maybe this isn't a bug since the documentation doesn't say much about what fromHTML() exactly does, but it's a problem for me nonetheless. If the provided string contains two or more spaces in sequence, fromHTML() removes all but one:

Html.fromHtml("Test   123").toString()
     (java.lang.String) Test 123

If I replace the spaces with   it seems to behave as expected, but causes me grief in other parts of my program:

Html.fromHtml("Test  123").toString()
     (java.lang.String) Test  123

Is this expected behavior?

Upvotes: 6

Views: 6735

Answers (5)

Amirhossein Ghasemi
Amirhossein Ghasemi

Reputation: 22138

Best approach works for me 100%

This answer works but cause side effect on some tag styles like <font color=#FFFFFF>Text</font>

To solve this problem just ignore one spaces with this way:

// htmlText = "This    is test";
public String fixDoubleSpaceIssue(String htmlText)
{
    htmlText= text.replace("   ", "&nbsp;&nbsp;&nbsp;");
    htmlText= text.replace("  ", "&nbsp;&nbsp;");
    return htmlText;
}

Upvotes: 2

PrincessLeiha
PrincessLeiha

Reputation: 3174

I used the following and it worked!

myText = myText.replaceAll(" ", "%20"); myText = Html.fromHtml(myText).toString(); myText = myText.replaceAll("%20", " ");

Upvotes: -3

Kiirani
Kiirani

Reputation: 1080

This is how HTML normally handles rendering of whitespace.

From the HTML Spec (emphasis mine):

Note that a sequence of white spaces between words in the source document may result in an entirely different rendered inter-word spacing (except in the case of the PRE element). In particular, user agents should collapse input white space sequences when producing output inter-word space. This can and should be done even in the absence of language information


The goal of the fromHtml function is to visually render the text based on the contained HTML, so it makes sense that it will follow HTML rendering rules as closely as possible.

If you'd like to preserve white space exactly, you could see if fromHtml() supports the <pre> tag?

Upvotes: 4

dannyroa
dannyroa

Reputation: 5571

Yes it is because that's how Html behaves.

Do something like this:

String myText = "Test   123";
Html.fromHtml(myText.replace(" ", "&nbsp;")).toString()

This way, it preserves the original value of your string.

Upvotes: 11

ianhanniballake
ianhanniballake

Reputation: 199805

as Html.fromHtml uses the same rules that a browser uses to parse the HTML, yes, it is expected that multiple spaces are collapsed into one as per this question and any other HTML reference.

Upvotes: 0

Related Questions