How to remove hard spaces with Jsoup?

Carlos Goce picture Carlos Goce · Jan 15, 2014 · Viewed 13k times · Source

I'm trying to remove hard spaces (from   entities in the HTML). I can't remove it with .trim() or .replace(" ", ""), etc! I don't get it.

I even found on Stackoverflow to try with \\u00a0 but didn't work neither.

I tried this (since text() returns actual hard space characters, U+00A0):

System.out.println( "'"+fields.get(6).text().replace("\\u00a0", "")+"'" ); //'94,00 '
System.out.println( "'"+fields.get(6).text().replace(" ", "")+"'" ); //'94,00 '
System.out.println( "'"+fields.get(6).text().trim()+"'"); //'94,00 '
System.out.println( "'"+fields.get(6).html().replace(" ", "")+"'"); //'94,00' works

But I can't figure out why I can't remove the white space with .text().

Answer

T.J. Crowder picture T.J. Crowder · Jan 15, 2014

Your first attempt was very nearly it, you're quite right that Jsoup maps   to U+00A0. You just don't want the double backslash in your string:

System.out.println( "'"+fields.get(6).text().replace("\u00a0", "")+"'" ); //'94,00'
// Just one ------------------------------------------^

replace doesn't use regular expressions, so you aren't trying to pass a literal backslash through to the regex level. You just want to specify character U+00A0 in the string.