如何选择用户无法输入的字符串分隔符,避免Split操作导致应用崩溃
Nice catch—this is a super common gotcha when using simple string concatenation for data serialization! Let's walk through your options to fix this reliably.
The key is to pick a character that's impossible for users to type into a standard input field via regular keyboard or input methods. Here are the best options:
Unicode Unit Separator (
U+001F): This is a control character specifically designed for separating data fields. It's non-printable, so users can't type it, and browsers won't render it. Perfect for your use case:// Concatenate with the unit separator const string = `${id}\u001F${listId}\u001F${inputValue}`; // Split back into the 3 values const [parsedId, parsedListId, parsedInputValue] = string.split('\u001F');This guarantees your split will always return an array of length 3, since the separator can never appear in user input.
Other Unicode Control Characters: Similar to the unit separator, characters like
U+001C(File Separator) orU+001D(Group Separator) work the same way—they're purpose-built for data splitting and untypeable by users.
While control characters solve the problem, there are even safer approaches that avoid separator issues entirely:
JSON Serialization: Wrap your data in an object and use JSON to convert it to/from a string. This is foolproof and more readable:
// Turn your data into a JSON string const dataString = JSON.stringify({ id, listId, inputValue }); // Parse it back to get the original values const { id: parsedId, listId: parsedListId, inputValue: parsedInputValue } = JSON.parse(dataString);No risk of separator conflicts, and this works seamlessly across most systems and storage solutions.
URL-Encode User Input: If you prefer sticking with a simple separator like
|, encode the user input first to escape any instances of the separator:// Encode the input before concatenation const string = `${id}|${listId}|${encodeURIComponent(inputValue)}`; // Split and decode to get the original input const [parsedId, parsedListId, encodedInput] = string.split('|'); const parsedInputValue = decodeURIComponent(encodedInput);This handles any special characters the user might type, not just
|.
内容的提问来源于stack exchange,提问作者Dzianis Czaplia

