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.

Answer from Explosion Pills on Stack Overflow
Discussions

javascript - Remove not alphanumeric characters from string - Stack Overflow
I want to convert the following string to the provided output. Input: "\\test\red\bob\fred\new" Output: "testredbobfrednew" I've not found any solution that will handle special More on stackoverflow.com
🌐 stackoverflow.com
removing all non-letter characters from a string? ((using regex))
This is very simple with regex. You just need to replace non-words (/\W/ig). So: var string = "lakjsdlkasjdlsaj@£$%^&*klajdlaskjds"; string.replace(/\W/ig, ""); --> "lakjsdlkasjdlsajklajdlaskjds" \w == words, \W == non words. You don't need a loop here as we're using /g which stands for global, so we replace every instance. And just incase I'm using /i as well which ignores the case. As it's regex you can just do /ig and the selectors will stack to ignore case and global. My favorite regex visualiser lives here: https://jex.im/regulex/#!embed=false&flags=ig&re=%5CW More on reddit.com
🌐 r/learnjavascript
10
4
September 28, 2015
regex - Remove all non alphanumeric and any white spaces in string using javascript - Stack Overflow
I'm trying to remove any non alphanumeric characters ANY white spaces from a string. Currently I have a two step solution and would like to make it in to one. var name_parsed = name.replace(/[^0-... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Replace all non alphanumeric characters, new lines, and multiple white space with one space - Stack Overflow
I'm looking for a neat regex solution to replace All non alphanumeric characters All newlines All multiple instances of white space With a single space For those playing at home (the following d... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Linux Genie
linuxgenie.net › home › javascript remove non-alphanumeric characters
JavaScript Remove non-Alphanumeric Characters - Linux Genie
June 16, 2023 - Call the replace() method that ... ... Another way to remove the non-alphanumeric characters from a string is using the “for” loop method....
🌐
GitHub
gist.github.com › protzi › 39fc8c5c9b5ad58fa3b2
Remove all non-alphanumeric characters (punctuation, spaces and symbols) · GitHub
Remove all non-alphanumeric characters (punctuation, spaces and symbols) Raw · nonNumerical.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Reddit
reddit.com › r/learnjavascript › removing all non-letter characters from a string? ((using regex))
r/learnjavascript on Reddit: removing all non-letter characters from a string? ((using regex))
September 28, 2015 -

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

Find elsewhere
🌐
Code Highlights
code-hl.com › home › javascript › tutorials
How to Remove Non Alphanumeric Characters JavaScript for Cleaner Code | Code Highlights
September 30, 2024 - If you want to preserve spaces between words while removing other non-alphanumeric characters, try this: ... The replace() method and regular expressions are well-supported across all major browsers, including Chrome, Firefox, Safari, and Edge.
🌐
Wikitechy
wikitechy.com › technology › remove-non-alphanumeric-characters
[ Solved -7 Answers] - How to remove non-alphanumeric characters from a string - Wikitechy
October 23, 2018 - To remove non-alphanumeric characters from a string,first you need to basically defined it as a regex. [pastacode lang=”javascript” manual=”preg_replace("/[^A-Za-z0-9 ]/", ”, $string); ” message=”JAVASCRIPT CODE” highlight=”” provider=”manual”/] For unicode characters, we have to use the below example: [pastacode lang=”javascript” manual=” preg_replace("/[^[:alnum:][:space:]]/u", ”, $string); ” message=”javascript code” highlight=”” provider=”manual”/] [ad type=”banner”]
🌐
TutorialsPoint
tutorialspoint.com › removing-all-non-alphabetic-characters-from-a-string-in-javascript
Removing all non-alphabetic characters from a string in JavaScript
March 18, 2025 - You can easily remove non-alphabetic characters from a string in JavaScript by using the above-mentioned methods. In this article, we have seen simple and efficient methods for removing non-alphabetic characters from a string.
🌐
CoreUI
coreui.io › answers › how-to-remove-special-characters-from-a-string-in-javascript
How to remove special characters from a string in JavaScript · CoreUI
May 20, 2026 - // Basic slug generator const slugify = (text) => { return text .toLowerCase() .trim() .replace(/[^\w\s-]/g, '') // remove non-word chars (except hyphens) .replace(/\s+/g, '-') // replace spaces with hyphens .replace(/-+/g, '-') // collapse consecutive hyphens .replace(/^-|-$/g, '') // trim leading/trailing hyphens } console.log(slugify('How to Remove Special Characters!!!')) // Result: 'how-to-remove-special-characters' console.log(slugify(' Hello, World!
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-strip-all-non-numeric-characters-from-string
JavaScript – Strip All Non-Numeric Characters From String | GeeksforGeeks
November 27, 2024 - Here are the different approaches ... remove specific text by replacing it with an empty string "". This meth ... The RegExp \D Metacharacter in JavaScript is used to search non-digit characters i.e all the characters except ...
Top answer
1 of 2
2

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.

2 of 2
1

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.

🌐
Tutorial Reference
tutorialreference.com › javascript › examples › faq › javascript-how-to-remove-non-alphanumeric-characters-from-string
How to Remove All Non-Alphanumeric Characters from a String in JavaScript | Tutorial Reference
This typically involves converting to lowercase, replacing spaces with hyphens, and removing all other non-alphanumeric characters. ... The String.prototype.replace() method, combined with a simple regular expression, provides a powerful and concise way to remove non-alphanumeric characters from a string. To remove everything except letters and numbers, use str.replace(/[^a-z0-9]/gi, '').
🌐
Melvin George
melvingeorge.me › blog › remove-all-non-alphanumeric-characters-string-javascript
How to remove all the non-alphanumeric characters from a string using JavaScript? | MELVIN GEORGE
June 23, 2021 - To remove all the non-alphanumeric characters from a string, we can use a regex expression that matches all the characters except a number or an alphabet in JavaScript.
🌐
Delft Stack
delftstack.com › home › howto › javascript › remove non alphanumeric characters using javascript
How to Remove Non Alphanumeric Characters Using JavaScript | Delft Stack
February 2, 2024 - The JSON.stringify() converts an object to a string, and the resulting string follows the JSON notation. This method is very useful if we want to replace non-alphanumeric characters in all elements of an array. Here, we discard everything except English alphabets (Capital and small) and numbers.