Remove special characters (like !, >, ?, ., # etc.,) from a string using JavaScript

Advertisement

Hi Guys, I would like to share a JavaScript snippet code which will remove special characters (like !, >, ?, ., # etc.,) from a string. Well – Recently I was working on a project where in which I want to remove some special characters from a given string or user entered string. Well for that I have written a JavaScript Code but it has taken 10 lines of code, I thought whether this is feasible and right way of practice, one of my friend has suggested to use Regular Expressions instead.

While surfing, I have downloaded a tutorial to learn Regular Expressions in JavaScript. It has helped me a lot – frankly to say – yes! there is a power in Regular Expressions. As I have explained above – for removing special characters from a String I have written 10 lines of code but after using Regular Expressions it has taken only 1 line of code – isn’t great.

Here is the code for removing special characters (like !, >, ?, ., # etc.,) from a string using JavaScript:

<script language="JavaScript"><!--
var temp = new String('This is a te!!!!st st>ring... So??? What...');
document.write(temp + '<br>');
temp =  temp.replace(/[^a-zA-Z 0-9]+/g,'');
document.write(temp + '<br>');
//--></script>

Please comment on the same, whether the above snippet is helpful to you guys.

Related Entries...

World News:

29 Responses

05.12.07

hi,
i hav used ur coading in firefox it is not working can u tel me the reason. Do i need to add any other code.

thx & rgds,
Ajay.

the following is my code…………
[CODE]
html>

function splrml(stringval){
alert(‘hi’);
temp = stringval.replace(/[^a-zA-Z 0-9] /g,”);
document.write(“hi”);
}

[/CODE]

05.12.07

Hi Ajay,

I think you have just copied the code which I have placed in my snippet, if you look at the code properly, while posting this article I have placed ‘ – (single quote – in keyboard – the key which is next to : but the browser has rendered in some other fashion like single quotation – if you want the above code to work in any browser, just copy the code and paste it in any tool like if you are using Dreamweaver, EditPlus, TextPad – just you need to do some necessary changes like I have mentioned above – single quotes, double quotes etc.,

Try this out, it will work definately (or else I will assist you in this regard).

Please let me know, Am I answered your question.

Thanks,
Admin

05.12.07

Hi author

This was very helpfull.

Kind regards
From a danish web delevoper

05.12.07

Hi Danish

Thanks for this.

05.12.07
05.12.07

HI i need your help i really want to create my own website/web page but i dont know how to go about doing it so can you please help me out

05.12.07

Hi,
I really needed this code thanks.

Mahendra

05.12.07

Nice work. worked on the first run.

05.12.07

Hi,

This was really helped. Modified the Reg Exp a bit so it could be used in my Java code.

regex = “[^a-zA-Z0-9]“;
unid = unid.replaceAll(regex,”");

Thanks.

05.12.07

Thank You!

Works great – one problem solved :)

05.12.07

I changed the text to

ring’s… So??? What…’);
document.write(temp + ”);
temp = temp.replace(/[^a-zA-Z 0-9]+/g,”);
document.write(temp + ”);
//–>

iam trying to replace the single quote also in “string’s”

help me
khp

05.12.07

Yes working..Thank you

05.12.07

Unfortunately, this works only for english texts.. I tried to write langugage-independent RegEx for that, but with no success. (Something like “any characters except ~ # $ % …”) Can somebody help?

05.12.07

You can use Javascript to validate special charecters.

function validateSpecialChars(myStringID)
{
// declare which special chars to validate
var strToSearch = myStringID.value;
var illegalChars = “‘”;
//var strToSearch = document.getElementById(myStringID).value;
for (var i = 0; i < strToSearch.length; i++)
{
if (illegalChars.indexOf(strToSearch.charAt(i)) != -1)
{
alert (“Special Charecter is not allowed”);
myStringID.focus();
return false;
}
}
}

05.12.07

Hi sabeer pasha,

Regular Expressions are more powerful that JavaScript string functions… Even for example, if you look at your code you have used so many lines of code, but if you look at my example I have used only one like of code using regexp. Not only this one, but to say frankly RegExp (Regular Expressions) are more powerful while developing.

My suggestion is to learn RegExp!…. It will help you in many ways…. and your job will be easier.

Thanks,
Vivek

05.12.07

Here is the RegExp I used for my AJAX call to get rid of invalid characters before sending the data to the server using POST:

/[^a-z A-Z 0-9 =&'.]/g

thanks

05.12.07

Hello,

I am using AJAX to get some information from one page and pass it to my main page.

The information I am getting contains a special character, the registered trademark

®

When the string comes through from the ajax routine it ends up as that unrecognizable box character

and ultimately as a ? question mark when the variable into which all of it is passed is rendered on the page.

I don’t actually need the ® character to render. But I need to get rid of the � ? that end up on the page. Is there a script / method for stripping out things like that?

Thanks

05.12.07

Hi Adam,

Firstly I would like to thank for your valuable comment in my blog.

Coming to your query, when you are using AJAX Calls and rendering the respective content on the page, once your request is complete and when the response is coming back try to render using CDATA (Character Data) this will get rid of all the special characters it will render how the content of the page was…

If you would like to have more information on CDATA, you can go through this page – http://www.w3schools.com/xmL/xml_cdata.asp

If you find any issues, please do mail me at vivek@developersnippets.com, if you have any small mockup kind of thing, please do share with me – I can write a code for you.

Thanks,
Vivek

05.12.07

Thats

its really worked.

i needed it to remove javascript errors

05.12.07

Thanks! It worked!

05.12.07

Thankx buddy..
This has saved a lot of time..
God bless

05.12.07

Hi Raju,

Thanks a lot…. :)

Thanks,
Vivek

05.12.07

Great tip thanks!

[...] This blog entry contains some helpful information about removing special characters from a string using javascript. I was able to modify it to be just a few of code in an onchange event. Just rename new_name to the attribute your correcting. [...]

05.12.07

I have a string “abc%ef”,

i need to replace % to d by using replace function in javascript.

how to do this.

05.12.07

i have a search string and i nedd to get rid off the characters -,?~!@#$%&*+-=”‘
i tried using the regular expression /[-,?~!@#$%&*+-="']/g
i’m using jQuery
my code is
var queryString = $(“#searchq”).val();
queryString = queryString.replace(/[-,?~!@#$%&*+-="']/g,”);
$(“#searchq”).val(queryString);
but unfortunately after using this it can be seen that even the digits get replaced.
also . gets replaced. whats wrong with my regular expresion

05.12.07

@Jayakrishnan Some of those characters need to be escaped.

@Nizamudeen,

[code]
'abc%efg'.replace(/%/gi,'D')
[/code]

should work.

I also recently discovered a way to do something similar to above (i.e. replace ‘%’ with ‘D’).

As an example, you might want to allow a user to fill in a text area including usage of letters ‘p’, ‘m’, ‘x’, and ‘d’ in place or arithmetic operators ‘+’, ‘-’, ‘*’, and ‘/’.

Note p, m, x, and d are abbreviations for ‘plus’, ‘minus’, ‘times’ (x), and ‘divide’.

The reason for this might be to save time when typing numerous short formulas. (Formulae? anyway…) So to save from having to use the Shift+’=’ (for ‘+’) and Shift+8 (for ‘*’), you may type “3p4″ for “3+4″, etc.

Anyway, so this is reversible as well, but the way to solve it using my example above is with a statement/function similar to this:
‘+-*/’.charAt(‘pmxd’.indexOf(operator))
where ‘operator’ is the p, m x, or d which you have to discover before applying the “search & replace”-like function…

You’d probably need to use regexp’s with match/search/replace if you needed to do the same with something that had char.length of greater than one…

Leave Your Response

* Name, Email, Comment are Required

Online Sponsors

Start Foreign Exchange Trading today with the Forex Affiliate Program and also you can have access Online Forex News to know what happens every single moment.


Forex Floor