我接收用户输入的JS代码,并实时执行以展示输出。
有时代码中会有零宽空格;这真的很奇怪。我不知道用户是如何输入的。例如:"($".length === 3
我需要能够从我的JS代码中删除该字符。我该如何做?或者也许有其他方法来执行该JS代码,以使浏览器不考虑这些零宽度空格字符吗?
我接收用户输入的JS代码,并实时执行以展示输出。
有时代码中会有零宽空格;这真的很奇怪。我不知道用户是如何输入的。例如:"($".length === 3
我需要能够从我的JS代码中删除该字符。我该如何做?或者也许有其他方法来执行该JS代码,以使浏览器不考虑这些零宽度空格字符吗?
Unicode有以下零宽字符:
在JavaScript中从字符串中删除它们,可以使用一个简单的正则表达式:
var userInput = 'a\u200Bb\u200Cc\u200Dd\uFEFFe';
console.log(userInput.length); // 9
var result = userInput.replace(/[\u200B-\u200D\uFEFF]/g, '');
console.log(result.length); // 5
请注意,还有许多可能不可见的符号。例如,ASCII控制字符中的一些。
var s = "\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude18\ud83d\ude18\ud83d\ude18"
<-- 包含实际的 \u200c 和 d。 - mplungjan我遇到一个问题,一些不可见字符破坏了我的JSON数据,导致出现Unexpected Token ILLEGAL异常,从而导致我的网站崩溃。
这是我的解决方案,使用RegExp变量:
var re = new RegExp("\u2028|\u2029");
var result = text.replace(re, '');
关于Javascript和零宽度空格的更多内容,你可以在这里找到: 零宽度空格
h
,然后是一串元数据凭据,最后是i
。但源和目标只显示单词“hi”。要防止这些零宽度野蛮人及其波斯信使进入斯巴达护城河将是一场斗争。悲哀! - Eric Leschinskistr.replace(/\u200B/g,'');
200B是零宽度空格8203的十六进制表示。将其替换为空字符串即可删除它。
[].filter.call( str, function( c ) {
return c.charCodeAt( 0 ) !== 8203;
} );
[].filter.call(strVal, c => c.charCodeAt() !== 8203).join('')
- Grant Humphries/([\u200B]+|[\u200C]+|[\u200D]+|[\u200E]+|[\u200F]+|[\uFEFF]+)/g
submit.onclick = evt => {
const stringToTrim = stringValue.value;
zeroWidthTrim(stringToTrim);
}
/**
* Given a string, when it has zero-width spaces in it, then remove them
*
* @param {String} stringToTrim The string to be trimmed of unicode spaces
*
* @return the trimmed string
*
* Regex for zero-width space Unicode characters.
*
* U+200B zero-width space.
* U+200C zero-width non-joiner.
* U+200D zero-width joiner.
* U+200E left-to-right mark.
* U+200F right-to-left mark.
* U+FEFF zero-width non-breaking space.
*/
function zeroWidthTrim(stringToTrim) {
const ZERO_WIDTH_SPACES_REGEX = /([\u200B]+|[\u200C]+|[\u200D]+|[\u200E]+|[\u200F]+|[\uFEFF]+)/g;
console.log('stringToTrim = ' + stringToTrim);
const trimmedString = stringToTrim.replace(ZERO_WIDTH_SPACES_REGEX, '');
console.log('trimmedString = ' + trimmedString);
return trimmedString;
};
<form runat="server">
<input name="stringValue" id="stringValue" type="text" placeholder="enter your string" value="[​‌]" />
<input type="button" value="remove zero-width characters" id="submit" />
</form>
stringToTrim
值和 trimmedString
值粘贴到 regex101 测试窗口 中,您会发现 Unicode 字符已从 trimmedString
值中去掉。