简体   繁体   English

如何从jQuery中的字符串中删除特殊字符,如$,@,%

[英]How to remove special characters like $, @, % from string in jquery

I have a string and I want to remove special characters like $, @, % from it. 我有一个字符串,我想从中删除特殊字符,例如$,@,%。

var str = 'The student have 100% of attendance in @school';

How to remove % and $ or other special characters from above string using jquery. 如何使用jQuery从字符串上方删除%和$或其他特殊字符。 Thank you. 谢谢。

If you know the characters you want to exclude, use a regular expression to replace them with the empty string: 如果知道要排除的字符,请使用正则表达式将其replace为空字符串:

 var str = 'The student have 100% of attendance in @school'; console.log( str.replace(/[$@%]/g, '') ); 

Or, if you don't want to include any special characters at all, decide which characters you do want to include, and use a negative character set instead: 或者,如果你不想包含任何特殊字符可言,决定想要的文字内容,然后用一个否定的字符集,而不是:

 var str = 'The student have 100% of attendance in @school'; console.log( str.replace(/[^a-z0-9,. ]/gi, '') ); 

The pattern 模式

[^a-z0-9,. ]

means: match any character other than an alphanumeric character, or a comma, or a period, or a space (and it will be replaced with '' , the empty string, and removed). 意思是:匹配字母数字字符,逗号,句点或空格以外的任何字符(它将替换为'' ,空字符串并删除)。

您可以使用正则表达式替换从字符串中删除特殊字符:

str.replace(/[^a-z0-9\s]/gi, '')

To remove special characters from the string we can use string replace function in javascript . 要从字符串中删除特殊字符,我们可以在javascript中使用字符串替换功能。

Eg. 例如。

var str = 'The student have 100% of attendance in @school';

alert(str.replace(/[^a-zA-Z ]/g, ""));

This will remove all special character except space 这将删除除空格以外的所有特殊字符

You should explore Regex. 您应该探索正则表达式。

Try this: 尝试这个:

 var str = 'The student have 100% of attendance in @school'; str= str.replace(/[^\\w\\s]/gi, '') document.write(str); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM