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.
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>
javascript - Remove not alphanumeric characters from string - Stack Overflow
removing all non-letter characters from a string? ((using regex))
regex - Remove all non alphanumeric and any white spaces in string using javascript - Stack Overflow
javascript - Replace all non alphanumeric characters, new lines, and multiple white space with one space - Stack Overflow
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.
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'.
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
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.
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.
At least in other languages, invoking the regular expressions engine is expensive. I'm not sure if that's true of JavaScript, but here's how you'd do it "C-style". I'm sure benchmarking its performance yourself will be a valuable learning experience.
var x = "Well Done!";
var y = "";
var c;
for (var i = 0; i < x.length; i++)
{
c = x.charCodeAt(i);
if (c >= 48 && c <= 57 || c >= 97 && c <= 122)
{
y += x[i];
}
else if (c >= 65 && c <= 90)
{
y += String.fromCharCode(c+32);
}
else if (c == 32 || c >= 9 && c <= 13)
{
y += '-';
}
}
$('#output').html(y);
See http://www.asciitable.com/ for ASCII codes. Here's a jsFiddle. Note that I've also implemented your toLowerCase() simply by adding 32 to the uppercase letters.
Disclaimer
Personally of course, I prefer readable code, and therefore prefer regular expressions, or using some kind of a strtr function if one exists in JavaScript. This answer is purely to educate.
Note: I thought I could come up with a faster solution with a single regex, but I couldn't. Below is my failed method (you can learn from failure), and the results of a performance test, and my conclusion.
Efficiency can be measured many ways. If you wanted to reduce the number of functions called, then you could use a single regex and a function to handle the replacement.
([A-Z])|(\s)|([^a-z\d])
REY
The first group will have toLowerCase() applied, the second will be replaced with a - and the third will return nothing. I originally used + quantifier for groups 1 and 3, but given the expected nature of the text, removing it result in faster execution. (thanks acheong87)
'Well Done!'.replace(/([A-Z])|(\s)|([^a-z\d])/g, function (match, $0, $1) {
if ($0) return String.fromCharCode($0.charCodeAt(0) + 32);
else if ($1) return '-';
return '';
});
jsFiddle
Performance
My method was the worst performing:
Acheong87 fastest
Original 16% slower
Mine 53% slower
jsPerf
Conclusion
Your method is the most efficient in terms of code development time, and the performance penalty versus acheong87's method is offset by code maintainability, readability, and complexity reduction. I would use your version unless speed was of the utmost importance.
The more optional matches I added to the regular expression, the greater the performance penalty. I can't think of any advantages to my method except for the function reduction, but that is offset by the if statements and increase in complexity.