Javascript Javascript用空字符串替换特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4537227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript replace special chars with empty strings
提问by SoLoGHoST
Ok, I have these string prototypes to work with, however, I don't understand what they do exactly.
好的,我有这些字符串原型可以使用,但是,我不明白它们到底是做什么的。
String.prototype.php_htmlspecialchars = function()
{
return this.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
String.prototype.php_unhtmlspecialchars = function()
{
return this.replace(/"/g, '"').replace(/>/g, '>').replace(/</g, '<').replace(/&/g, '&');
}
String.prototype.php_addslashes = function()
{
return this.replace(/\/g, '\\').replace(/'/g, '\\'');
}
String.prototype._replaceEntities = function(sInput, sDummy, sNum)
{
return String.fromCharCode(parseInt(sNum));
}
String.prototype.removeEntities = function()
{
return this.replace(/&(amp;)?#(\d+);/g, this._replaceEntities);
}
String.prototype.easyReplace = function (oReplacements)
{
var sResult = this;
for (var sSearch in oReplacements)
sResult = sResult.replace(new RegExp('%' + sSearch + '%', 'g'), oReplacements[sSearch]);
return sResult;
}
Basically, what I need to do is replace all instances of double quotes ("), >, <, single quotes ('), etc. etc.. Basically the same stuff that htmlentities() in php changes, but I need to replace them with an empty string, so that they are removed from the text.
基本上,我需要做的是替换双引号 (")、>、<、单引号 (') 等的所有实例。基本上与 php 中的 htmlentities() 更改的内容相同,但我需要替换它们带有一个空字符串,以便从文本中删除它们。
Can I use any of the functions above? If not, how can I accomplish this in Javascript? Can I use a replace on the string?
我可以使用上述任何功能吗?如果没有,我如何在 Javascript 中完成此操作?我可以在字符串上使用替换吗?
Please, someone, help me here. I am placing this text into a select box and will be inputted into the database upon submitting of the form. Though, I am using PHP to remove all of these characters, however, I'm having difficulty finding a way to do this in Javascript.
请有人在这里帮助我。我将此文本放入一个选择框中,并将在提交表单后输入到数据库中。虽然,我正在使用 PHP 来删除所有这些字符,但是,我很难找到在 Javascript 中执行此操作的方法。
Thanks :)
谢谢 :)
回答by Naveed
Remove special characters (like !, >, ?, ., # etc.,) from a string using JavaScript:
使用 JavaScript 从字符串中删除特殊字符(如 !、>、?、.、# 等):
var temp = new String('This is a te!!!!st st>ring... So??? What...');
document.write(temp + '<br>');
temp = temp.replace(/[^a-zA-Z 0-9]+/g,'');
document.write(temp + '<br>');
Edit:
编辑:
If you don't want to remove dot(.) from string:
如果您不想从字符串中删除 dot(.):
temp = temp.replace(/[^a-zA-Z 0-9.]+/g,'');