Strip Character and Whitespace in JavaScript Function

Strip Character and Whitespace in JavaScript Function

By Shawn Olson

Posted on January 7th, 2004

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.
Copyright © 2004-2010 by Shawn Olson.

Subscribe to this guestbookComments on Strip Character and Whitespace in JavaScript Function

Otto Teixeira said:

Why not use the built in replace() function?
string.replace(/,/g, "");

louis tsoi said:

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

sitemap RGB Color Columbus Photography Free Word Search Maker monty hall game Hangman John Dewey