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

Answer from Jonny 5 on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-program-to-remove-non-alphanumeric-characters-from-a-string
JavaScript Program to Remove Non-Alphanumeric Characters from a String - GeeksforGeeks
July 23, 2025 - Regular expressions offer a concise way to match and remove non-alphanumeric characters. We can use the replace() method with a regular expression to replace all non-alphanumeric characters with an empty string.
Discussions

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
javascript - Regex to remove all non alpha-numeric and replace spaces with + - Stack Overflow
OP wants to replace every occurrence of space or non-alphanumeric symbol with JUST ONE '+' sign....durarara+x2+ten is desired result.... 2015-08-19T22:32:09.63Z+00:00 ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Stack Overflow chat opening up to all users in January; Stack Exchange chat... 29 Remove all characters except alphanumeric and spaces with javascript... More on stackoverflow.com
🌐 stackoverflow.com
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
Spinal case, regex
Tell us what’s happening: Why can’t the third line replace the code in the comments? I dont understand why a space can be used to replace anything other than a alphanumerical, but not a hypen. (this is not my original solution; just was trying some things out) Your code so far function ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
3
0
May 18, 2021
🌐
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 ... we can use a regex expression that matches all the characters except a number or an alphabet in JavaScript. // a string const str = "#HelloWorld123$%"; // regex expression to match all // non-alphanumeric characters in string const regex = /[^A-Za-z0-9]/g; // use replace() ...
🌐
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 - 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. The g modifier says global, and i matches case-insensitivity. var input = '123abcABC-_*(!@#$%^&*()_-={}[]:\"<>,.?/~`'; var stripped_string = input.replace(/[^a-z0-9]/gi, ''); console.log(stripped_string); ... We can optimize the regex used in the above code by replacing it with /[\W]/g where \W is equivalent to [^0-9a-zA-Z]. So, our final regex would be /[\W_]/g because we remove underscore from the input string.
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-remove-non-alphanumeric-characters-from-string
Remove all non-alphanumeric Characters from a String in JS | bobbyhadz
The removeNonAlphanumeric() function takes a string as a parameter and removes all non-alphanumeric characters from the string. You can also use the \W special character to shorten your regex and remove all non-alphanumeric characters from a string.
🌐
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

🌐
Irt
irt.org › script › 1583.htm
Q1583 How can I replace all non alphanumeric characters from a string?
<script language="JavaScript"><!-- var temp = new String('This is a test string... So??? What...'); document.write(temp + '<br>'); temp = temp.replace(/[^a-zA-Z 0-9]+/g,''); document.write(temp + '<br>'); //--></script>
Find elsewhere
🌐
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....
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Spinal case, regex - JavaScript
May 18, 2021 - Tell us what’s happening: Why can’t the third line replace the code in the comments? I dont understand why a space can be used to replace anything other than a alphanumerical, but not a hypen. (this is not my original solution; just was trying some things out) Your code so far function spinalCase(str) { return str.replace(/([A-Z])/g,' $1') .replace(/[^A-Za-z0-9]/g, '-') /* .replace(/[^A-Za-z0-9]/g, ' ') .replace(/\s{1,}/g, "-") */ .replace(/^\-|[\-]$/g, '') .toLowerCase(); } ...
🌐
TutorialsPoint
tutorialspoint.com › article › removing-all-non-alphabetic-characters-from-a-string-in-javascript
Removing all non-alphabetic characters from a string in JavaScript
March 15, 2026 - The regular expression /[^A-Za-z]/g matches any character that is NOT (^) a letter from A-Z or a-z. The 'g' flag ensures all matches are replaced globally. Using a for..of loop with character checking is another simple method of removing ...
🌐
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”] We can also use the regular expression.
Top answer
1 of 2
2

You're using toLowerCase when creating strReverse, and then comparing it with str. But str will still have upper-case characters in it. Additionally, you're leaving the non-alpha characters in str.

You also need to remove _ for the last one to work, which \W won't do on its own.

You need to first prep str, then create the reversed version of it, and do the check:

function palindrome(str) {
    var strReverse;
    str = str.toLowerCase().replace(/\W|_+/g,'');
    strReverse = str.split('').reverse().join('');
    return strReverse === str;
}

Live Example:

function palindrome(str) {
    var strReverse;
    str = str.toLowerCase().replace(/\W|_+/g,'');
    strReverse = str.split('').reverse().join('');
    return strReverse === str;
}
function test(str, expectedResult) {
    var result = palindrome(str);
    var p = document.createElement('p');
    p.className = !result == !expectedResult ? "good" : "bad";
    p.appendChild(document.createTextNode(str));
    document.body.appendChild(p);
}
test("eye", true);
test("race car", true);
test("not a palindrome", false);
test("A man, a plan, a canal. Panama", true);
test("never odd or even", true);
test("nope", false);
test("almostomla", false);
test("My age is 0, 0 si ega ym.", true);
test("1 eye for of 1 eye.", false);
test("0_0 (: /-\ :) 0-0", true);
.good {
  color: green;
}
.bad {
  color: #d00;
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

2 of 2
1

Try this function

function palindrome(str) {
    str=str.toLowerCase().replace(/[^A-Za-z]+/g, '');
    var strReverse = str.split('').reverse().join('');
    if(strReverse===str)
        return true;
    else
        return false;
}

Issue in your code was that when you were comparing the strReverse with str, strReverse was formatted but str was not. Like you didn't remove special characters and spaces and numbers from str, you didn't made it lowercase etc.

Check this fiddle for every test case

🌐
Regex101
regex101.com › r › jI5hK6 › 1
regex101: Remove Non-Alphanumeric Characters
Online regex tester and debugger. Test, explain, benchmark, and generate code for PCRE2, JavaScript, Python, Go, Java, .NET, and Rust.
🌐
Itsourcecode
itsourcecode.com › home › how to remove all non-alphanumeric characters in javascript?
How to remove all non-alphanumeric characters in JavaScript? - Itsourcecode.com
June 27, 2023 - To remove all non-alphanumeric characters from a string in JavaScript, you can use the String.replace() method to get rid of any characters in a string that are not letters or numbers.