[英]custom jquery or javascript remove special characters from a string extension
I would like to be able to do this:我希望能够做到这一点:
var test = "A3%2345-S63.][343\g30.1.0.45";
test.removeSpecialCharacters();
all special characters ie (%,*, (,[..etc) will be removed);所有特殊字符,即 (%,*, (,[..etc) 将被删除);
or或者
test.removeSpecialCharacters("-");
meaning all special characters will be replaced with "-"意味着所有特殊字符都将替换为“-”
I've tried with this but i don't think i'm doing it right :(我试过这个,但我认为我做得不对:(
jQuery.fn.removeSpecialCharacters = function (optional replaceWith) {
this.replace(/[^a-z0-9\s]/gi, '');
}
There is absolutely no reason to use jQuery for this.绝对没有理由为此使用 jQuery。 Adding the function to jQuery.fn
would make it a method usable on jQuery objects.将函数添加到jQuery.fn
将使其成为可用于 jQuery 对象的方法。 However, you want it for strings.但是,您希望它用于字符串。 They are instances of String
so you need to extend String.prototype
instead:它们是String
实例,因此您需要扩展String.prototype
:
String.prototype.removeSpecialChars = function(replaceWith) {
return this.replace(/[^a-z0-9\s]/gi, replaceWith || '');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.