You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何选择用户无法输入的字符串分隔符,避免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.

Using a Separator Users Can't Input

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) or U+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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:37:33