1

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.

Shriya
  • 35
  • 1
  • 2
  • 9
  • Please look at https://stackoverflow.com/questions/8979619/jquery-remove-special-characters-from-string-and-more Seems like a duplicate question – Mulli Jan 22 '19 at 06:09
  • Possible duplicate of [jQuery remove special characters from string and more](https://stackoverflow.com/questions/8979619/jquery-remove-special-characters-from-string-and-more) – Icehorn Jan 22 '19 at 06:12
  • please check this solution - . – ysk Jan 22 '19 at 06:12

4 Answers4

3

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).

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

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

killer
  • 11
  • 2
1

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>
deeepss
  • 153
  • 1
  • 10
0

You can use a regex replace to remove special characters from a string:

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