Replace [^a-zA-Z0-9 -] with an empty string.
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
Answer from Amarghosh on Stack OverflowReplace [^a-zA-Z0-9 -] with an empty string.
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
I could have used RegEx, they can provide elegant solution but they can cause performane issues. Here is one solution
char[] arr = str.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
|| char.IsWhiteSpace(c)
|| c == '-')));
str = new string(arr);
When using the compact framework (which doesn't have FindAll)
Replace FindAll with1
char[] arr = str.Where(c => (char.IsLetterOrDigit(c) ||
char.IsWhiteSpace(c) ||
c == '-')).ToArray();
str = new string(arr);
1 Comment by ShawnFeatherly
removing all non-letter characters from a string? ((using regex))
How to find and remove non-alphanumeric character from a column - Oracle Forums
Replace non-alphanumeric characters from string
neovim - Regex for any character that is not alphanumeric, whitespace, or a doublequote - Vi and Vim Stack Exchange
I am currently trying this two different ways and they aren't working - I'm checking the input value and running this every time a key is pressed:
input.replace(/[^a-zA-z]/, "");
and
for(var i = 0; i < input.length; i++){
if( input[i] == /[^a-zA-z]/g){
console.log("input " + input[i] + " is not a letter!");
input.replace(input[i], "");
}
}jsfiddle here
Why would:
var replaceChar=str.replace(/[^A-Za-z0-9]/g, '');
replace all non-alphanumeric characters?
Why does (/[A-Za-z0-9]/g, ''); signify them? More like, how? Can someone please give a ELI5 explanation? I saw it on StackOverFlow, but the explanation is going over my head.