Strip Zero Width Chars From Pasted Text

Pasted text hides U+200B and U+FEFF characters that trim and strip keep: drop code points whose Unicode category is FORMAT to clean them reliably.

JavaForm Validation

Code

snippet
public class InvisibleCharCleaner {

    public static void main(String[] args) {
        // U+200B ZERO WIDTH SPACE 与 U+FEFF BOM:肉眼不可见,却计入长度
        String pasted = "pay\u200Bload\uFEFF";

        // trim/strip 只认 isWhitespace:零宽字符不属于空白,原样保留
        System.out.println("isWhitespace(U+200B): " + Character.isWhitespace('\u200B'));
        System.out.println("length before       : " + pasted.length());

        String cleaned = stripFormat(pasted);
        System.out.println("length after        : " + cleaned.length());
        System.out.println("cleaned             : [" + cleaned + "]");
    }

    // 按通用类别过滤:FORMAT(Cf)承载零宽字符与 BOM
    static String stripFormat(String text) {
        StringBuilder out = new StringBuilder(text.length());
        text.codePoints()
                .filter(cp -> Character.getType(cp) != Character.FORMAT)
                .forEach(out::appendCodePoint);
        return out.toString();
    }
}

Walking through the code

Strip Zero Width Chars From Pasted Text reduces to the class InvisibleCharCleaner and the functions main and stripFormat.

What to watch for

  • Nothing arrives from a registry; the language ships every API used.

Using it

The signature to anchor on: public static void main(String[] args)

Output lines are prefixed (isWhitespace(U+200B):, length before :, length after :), and each step’s outcome is easy to spot.

main calls 1 helper in sequence: stripFormat.

Key statements

return out.toString();
.filter(cp -> Character.getType(cp) != Character.FORMAT)
.forEach(out::appendCodePoint);

Interactive Tools for This Topic

FAQ

What does Strip Zero Width Chars From Pasted Text print when run?
No setup needed: run the file and look for labeled lines like `isWhitespace(U+200B):`, `length before :`, `length after :` in the output.