【问题标题】:Javascript : Detect illegal arrows unicode and replace with blankJavascript:检测非法箭头unicode并替换为空白
【发布时间】:2020-07-16 09:22:12
【问题描述】:

非法箭头:escape(strNotes):结果 -> "%1A"

这是非法箭头:https://www.htmlsymbols.xyz/unicode/U+001A

我无法粘贴 strNotes,但系统中的 strNotes 被替换为非法箭头字符,这会破坏系统。

正确的箭头:escape('→'):结果 -> "%u2192"

但是如果我使用上面的proper arrow,效果很好。

如何检测 Javascript 中的 Illegals 箭头和特殊字符并将其从 String 中删除?

【问题讨论】:

  • 请发帖strNotes
  • 如果我尝试粘贴它,那么保存后它就会消失。我正在发布它的照片。
  • %1A 是一个控制字符 en.wikipedia.org/wiki/Substitute_character。你应该先弄清楚它是如何到达那里的stackoverflow.com/questions/17024436
  • @devio 所以这些笔记是来自某个系统的复制粘贴。这是否意味着还有其他类似的字符,如果是这样,我们如何将它们替换为blank

标签: javascript unicode utf-8


【解决方案1】:

感谢@devio,我最终做到了

    String.prototype.toUnicode = function () {
        var uni = [],
            i = this.length;
        while (i--) {
            uni[i] = this.charCodeAt(i);
        }
        return "&#" + uni.join(';&#') + ";";
    };

    let setOfIllegalCharacters = new Set();
    for (let i = 0; i < 32; i++) {
        setOfIllegalCharacters.add("&#" + i + ";");
    }


        // this iterates through the strNotes string and removes all illegal or bad characters.
        for (let i = 0; i < strNotes.length; i++) {
            if (setOfIllegalCharacters.has(strNotes[i].toUnicode())) {
                strNotes = strNotes.replace(strNotes[i], '');
            }
        }

【讨论】:

    【解决方案2】:

    你可以替换ASCII字符

    text.replace(/[^\ -~]+/g, '')
    

    -~ 是减号 - ~

    【讨论】:

      【解决方案3】:

      您可以使用replace(/ /, ''),并将它们全部替换。

      【讨论】:

      • 使用类似这样的内容 ``` let specialChars = "!@#$^&%*()+=-[]\/{}|:?,."; for (let i = 0; i
      • 如果我知道我要替换什么,这会起作用,但就我而言,我不知道。
      • 只能保留字符 str.replace(/[^a-zA-Z ]/g, "")
      • @NagendraSingh 我以为你说这个字符是 \x1A,所以你会写 replace(/\x1A/g, '\u2192') 来用真正的箭头替换它。
      • 是的,实际上我运行了一个循环并包含来自https://www.htmlsymbols.xyz/unicode/U+001A 的所有字符,并在将每个字符转换为unicode 后删除了0 - 36 中的所有字符。并将其从字符串中删除。
      猜你喜欢
      • 2010-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 2016-07-04
      • 1970-01-01
      • 2020-11-08
      相关资源
      最近更新 更多