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. Thank you.
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. Thank you.
If you know the characters you want to exclude, use a regular expression to replace
them with the empty string:
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).
To remove special characters from the string we can use string replace function in 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>
You can use a regex replace to remove special characters from a string:
str.replace(/[^a-z0-9\s]/gi, '')