Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created May 23, 2019 17:58
Show Gist options
  • Save topherPedersen/51148f511ca64dc77357f5d203ca4bef to your computer and use it in GitHub Desktop.
Save topherPedersen/51148f511ca64dc77357f5d203ca4bef to your computer and use it in GitHub Desktop.
Stripping Special Characters from Strings in JavaScript without Regex
/*
Last night while working on my latest project, a personal finance application,
I ran across the need to strip certain (special) characters from a string of
user input in JavaScript. I assumed that there was an easy built in feature to
do this in JavaScript, but most of the examples I found either used Regex which
I don’t really want to use, or utilized some other confusing method that was
not particularly straight forward. So, I decided to go ahead and post my ugly
yet simple solution here on the blog in case anyone else might one day need it.
For my technique, I simply have one string variable that I want to strip special
characters from, and another empty string which I will append characters from
the original string excluding any special characters that I want to ‘strip’:
*/
var dollars = prompt("Enter a dollar value with or without $ and . characters:");
var dollarsClean = "";
var isNumberOrDecimal = false;
// loop through characters and build new string
for (var i = 0; i < dollars.length; i++) {
// check for desired characters
if (dollars.substr(i, 1) === '0') {
isNumberOrDecimal = true;
} else if (dollars.substr(i, 1) === '1') {
isNumberOrDecimal = true;
} else if (dollars.substr(i, 1) === '2') {
isNumberOrDecimal = true;
} else if (dollars.substr(i, 1) === '3') {
isNumberOrDecimal = true;
} else if (dollars.substr(i, 1) === '4') {
isNumberOrDecimal = true;
} else if (dollars.substr(i, 1) === '5') {
isNumberOrDecimal = true;
} else if (dollars.substr(i, 1) === '6') {
isNumberOrDecimal = true;
} else if (dollars.substr(i, 1) === '7') {
isNumberOrDecimal = true;
} else if (dollars.substr(i, 1) === '8') {
isNumberOrDecimal = true;
} else if (dollars.substr(i, 1) === '9') {
isNumberOrDecimal = true;
} else if (dollars.substr(i, 1) === '.') {
isNumberOrDecimal = true;
}
if (isNumberOrDecimal) {
dollarsClean += dollars.substr(i, 1);
}
// set variable back to false for next iteration of the loop
isNumberOrDecimal = false;
}
alert(dollarsClean);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment