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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.