我想使用JavaScript从字符串中删除除空格之外的所有特殊字符。
例如, 美国广播公司的测试#年代 应输出为 abc测试。
我想使用JavaScript从字符串中删除除空格之外的所有特殊字符。
例如, 美国广播公司的测试#年代 应输出为 abc测试。
当前回答
试试这个:
const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
其他回答
我不知道JavaScript,但它不是可能使用正则表达式?
像[^\w\d\s]这样的东西可以匹配除数字、字符和空白之外的任何东西。在JavaScript中找到语法只是一个问题。
正则表达式
let string = "!#This tool removes $special *characters* /other/ than! digits, characters and spaces!!!$";
var NewString= string.replace(/[^\w\s]/gi, '');
console.log(NewString);
结果//删除除数字、字符和空格以外的特殊字符
实例:https://helpseotools.com/text-tools/remove-special-characters
你可以指定你想要删除的字符:
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
或者,要更改除数字和字母以外的所有字符,请尝试:
string = string.replace(/[^a-zA-Z0-9]/g, '');
试着用这个
var result= stringToReplace.replace(/[^\w\s]/g, '')
[^]表示否定,\w表示[a-zA-Z0-9_]字字符,\s表示空格, /[]/g表示全局
我尝试了Seagul非常有创意的解决方案,但发现它也将数字视为特殊字符,这并不适合我的需求。以下是我对Seagul解决方案的(故障保险)调整……
//return true if char is a number
function isNumber (text) {
if(text) {
var reg = new RegExp('[0-9]+$');
return reg.test(text);
}
return false;
}
function removeSpecial (text) {
if(text) {
var lower = text.toLowerCase();
var upper = text.toUpperCase();
var result = "";
for(var i=0; i<lower.length; ++i) {
if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '')) {
result += text[i];
}
}
return result;
}
return '';
}