Strip Character and Whitespace in JavaScript Function

Posted Jan 6, 2004
Last Updated Nov 3, 2011

This JavaScript function will strip every instance of any specified character (including whitespace) from a string in JavaScript.

Function Name: stripCharacter(words,character)

Example of output:

string="This , is , a , broken , sentence.";
string = stripCharacter(string,',');

The string converts to "This is a broken sentence."

To use this script, copy this link and place it in the head of your HTML before any other JavaScript that may use it.

<script type="text/javascript" src="http://www.shawnolson.net/scripts/public_smo_scripts.js"></script>


Please include credit when using this script and read this site's Terms & Conditions before using.

One known issue is that to strip a whitespace, you may have to type stripCharacter(string,' ') rather than stripCharacter(string," ") -- for some reason the double quotes has errors.


2011-11-03 This was one of the first JavaScript functions I shared. It is actually a very primitive function that is only useful if you are brand new to JavaScript and don't have time/need to actually learn JavaScript... as the function can be handled very easily with standard JavaScript string functions.

Comment

No HTML Tags are permitted.

Otto Teixeira

Oct 5, 2009

Why not use the built in replace() function?

string.replace(/,/g, "");

Shawn Olson

Oct 5, 2009





Otto... yes, your question is very good. I cannot say why I chose to write a custom function to handle that. There may have been some quirk in one of the browsers back then... it's hard to say. I may not have been thinking clearly due to working late or sipping too much wine!





Thanks for the input.

louis tsoi

Apr 4, 2007

Hi.. inside your strip function there is a loop that begins from 1. That should be changed to 0. I was experiementing with it to remove spaces and return characters as a way to validate form input.. but your function was returing back a space everytime which was incorrect.



Anyway it should look like this:

function stripCharacter(words,character)

{

var spaces = words.length;

for(var x = 0; x
Angry Teapot Level Design Awards

Newsletter Subscription