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.

3

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.