我尝试从字符串中删除一些不安全的字符,但我相信我的 RegExp 对象有问题。
我在下面尝试做的是,如果有字符的编码长度大于 3 个字符,则应将其替换为空格。
因此,如果编码值为 %3D
,即 =
符号,则可以在我的字符串中包含。但如果是 '
撇号 %E2%80%99
则应替换为空格。
val = "Angelina’s";
valEnc = encodeURIComponent(val);
for(var i = 0; i < val.length; i++){
var a = val.substr(i,1);
if(encodeURIComponent(a).length > 3){
console.log(a, encodeURIComponent(a));
var re = new RegExp(encodeURIComponent(a),"ig");
valEnc.replace(re," ");
};
};
console.log(decodeURIComponent(valEnc));
此代码有效并记录不需要的字符,但不能用空格替换它们,我做错了什么?谢谢。
最佳答案
您似乎在这里不必要地使用了正则表达式。一种方法是一次构建一个字符的结果字符串:
val = "Angelina’s";
valEnc = "";
for(var i = 0; i < val.length; i++){
var a = val.substr(i,1);
var e = encodeURIComponent(a);
if(e.length <= 3){
valEnc += e;
}
}
console.log(decodeURIComponent(valEnc));
关于javascript - 从字符串中剥离一些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3375838/