在将字符串传递给 encodeURIComponent() 之前从字符串中排除字符

Exclude characters from string before passing it to encodeURIComponent()

如果字符串包含区间 U+D800..U+DFFF 中的字符,则 encodeURIComponent() 会引发 malformed URI sequence 错误。我想在将给定字符串传递给 encodeURIComponent() 之前从给定字符串中删除这些字符。怎么做?

示例: 我有一个以 UTF-16BE 编码的文本文件,其中包含以下六角字符:

D7FF D800 D801 ... DFFE DFFF E000

我正在搜索一个函数,其中 returns 这个字符串来自上面的字符串:

D7FF E000

因此只保留有效的 Unicode 字符。

您可以使用 replace/encodeURIComponent 组合来获得所需的结果。您首先需要使用此正则表达式匹配所有不属于 unicode 范围 [0xD800..0xDFFF] 的字符:/[^\uD800-\uDFFF]+/g 然后用它们的编码版本替换它们:

let result = string.replace(/[^\uD800-\uDFFF]+/g, match => encodeURIComponent(match));

示例:

let string = "/foo/\uD7FF\uD800\uD801/bar";

let result = string.replace(/[^\uD800-\uDFFF]+/g, match => encodeURIComponent(match));

console.log(result);