2

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

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, '');
}
2
  • Why would you use jQuery for this? Commented Nov 16, 2012 at 13:25
  • 1
    jquery elements are not strings, your extension makes sense as a string prototype, not a jquery extension. Commented Nov 16, 2012 at 13:38

1 Answer 1

3

There is absolutely no reason to use jQuery for this. Adding the function to jQuery.fn would make it a method usable on jQuery objects. However, you want it for strings. They are instances of String so you need to extend String.prototype instead:

String.prototype.removeSpecialChars = function(replaceWith) {
    return this.replace(/[^a-z0-9\s]/gi, replaceWith || '');
}
Sign up to request clarification or add additional context in comments.

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.