Removing non-alphanumeric chars
The following is the/a correct regex to strip non-alphanumeric chars from an input string:
input.replace(/\W/g, '')
Note that \W is the equivalent of [^0-9a-zA-Z_] - it includes the underscore character. To also remove underscores use e.g.:
input.replace(/[^0-9a-z]/gi, '')
The input is malformed
Since the test string contains various escaped chars, which are not alphanumeric, it will remove them.
A backslash in the string needs escaping if it's to be taken literally:
"\\test\\red\\bob\\fred\\new".replace(/\W/g, '')
"testredbobfrednew" // output
Handling malformed strings
If you're not able to escape the input string correctly (why not?), or it's coming from some kind of untrusted/misconfigured source - you can do something like this:
JSON.stringify("\\test\red\bob\fred\new").replace(/\W/g, '')
"testredbobfrednew" // output
Note that the json representation of a string includes the quotes:
JSON.stringify("\\test\red\bob\fred\new")
""\\test\red\bob\fred\new""
But they are also removed by the replacement regex.
Answer from AD7six on Stack OverflowRemoving non-alphanumeric chars
The following is the/a correct regex to strip non-alphanumeric chars from an input string:
input.replace(/\W/g, '')
Note that \W is the equivalent of [^0-9a-zA-Z_] - it includes the underscore character. To also remove underscores use e.g.:
input.replace(/[^0-9a-z]/gi, '')
The input is malformed
Since the test string contains various escaped chars, which are not alphanumeric, it will remove them.
A backslash in the string needs escaping if it's to be taken literally:
"\\test\\red\\bob\\fred\\new".replace(/\W/g, '')
"testredbobfrednew" // output
Handling malformed strings
If you're not able to escape the input string correctly (why not?), or it's coming from some kind of untrusted/misconfigured source - you can do something like this:
JSON.stringify("\\test\red\bob\fred\new").replace(/\W/g, '')
"testredbobfrednew" // output
Note that the json representation of a string includes the quotes:
JSON.stringify("\\test\red\bob\fred\new")
""\\test\red\bob\fred\new""
But they are also removed by the replacement regex.
All of the current answers still have quirks, the best thing I could come up with was:
string.replace(/[^A-Za-z0-9]/g, '');
Here's an example that captures every key I could find on the keyboard:
var string = '123abcABC-_*(!@#$%^&*()_-={}[]:\"<>,.?/~`';
var stripped = string.replace(/[^A-Za-z0-9]/g, '');
console.log(stripped);
Outputs: '123abcABC'.
regex - Remove all non alphanumeric and any white spaces in string using javascript - Stack Overflow
javascript - Regex to remove all non alpha-numeric and replace spaces with + - Stack Overflow
regex - Remove all characters except alphanumeric and spaces with javascript - Stack Overflow
javascript - Removing non-alphanumeric text with String.prototype.replace - Stack Overflow
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
This is actually fairly straightforward.
Assuming str is the string you're cleaning up:
str = str.replace(/[^a-z0-9+]+/gi, '+');
The ^ means "anything not in this list of characters". The + after the [...] group means "one or more". /gi means "replace all of these that you find, without regard to case".
So any stretch of characters that are not letters, numbers, or '+' will be converted into a single '+'.
To remove parenthesized substrings (as requested in the comments), do this replacement first:
str = str.replace(/\(.+?\)/g, '');
function replacer() {
var str = document.getElementById('before').value.
replace(/\(.+?\)/g, '').
replace(/[^a-z0-9+]+/gi, '+');
document.getElementById('after').value = str;
}
document.getElementById('replacem').onclick = replacer;
<p>Before:
<input id="before" value="Durarara!!x2 Ten" />
</p>
<p>
<input type="button" value="replace" id="replacem" />
</p>
<p>After:
<input id="after" value="" readonly />
</p>
str = str.replace(/\s+/g, '+');
str = str.replace(/[^a-zA-Z0-9+]/g, "");
- First line replaces all the spaces with + symbol
- Second line removes all the non-alphanumeric and non '+' symbols.
input.replace(/[^\w\s]/gi, '')
Shamelessly stolen from the other answer. ^ in the character class means "not." So this is "not" \w (equivalent to \W) and not \s, which is space characters (spaces, tabs, etc.) You can just use the literal if you need.
I know this is an old thread, but so popular that appears at the top of a Google search. So, as an alternative, the accepted answer and comment from 3limin4t0r inspired me to:
.replace(/\W+/g, " ")
IMHO
const input = document.querySelector("input");
const button = document.querySelector("button");
const output = document.querySelector("output");
button.addEventListener("click", () => {
output.textContent = input.value.replace(/\W+/g, " ");
})
<input>
<button>Replace</button>
<p>
<output></output>
</p>
this.colorPreset1=this.colorPreset1.replace(/[^0-9a-zA-Z]/g, '');
The character group was changed to a exclusion group. [^] will match any character not in the list. As you had it, it would only match the characters you wanted to keep.
The anchors for the string were removed - You're wanting to replace any non-alpha numeric characters, so it doesn't matter where they're located.
The global flag //g was added so it will replace all matches instead of just the first one.
By adding ^ and $ around your regular expression, you explicitly tell it to match strings starting and ending with this pattern.
So it will replace the searched pattern only if if all the content of the string matches the pattern.
If you want to match each occurence of non numerical or alphabetical characters, you will have to remove the ^ start constraint and the $ end constraint, but also will have to change the pattern itself:
[A-Za-z0-9]
matches alphabetical or numerical characters, you want the opposite of that (to inverse a character class add a ^ at the start of the character class:
[^A-Za-z0-9]
finally add the g option to the regex to tell it to match each occurence (otherwise only the first occurence will be replaced):
/[^A-Za-z0-9]+/g
Be aware, that \W leaves the underscore. A short equivalent for [^a-zA-Z0-9] would be [\W_]
text.replace(/[\W_]+/g," ");
\W is the negation of shorthand \w for [A-Za-z0-9_] word characters (including the underscore)
Example at regex101.com
Jonny 5 beat me to it. I was going to suggest using the \W+ without the \s as in text.replace(/\W+/g, " "). This covers white space as well.