How to remove all non-alphanumeric characters in JavaScript?

Are you struggling with how to remove all non-alphanumeric characters from a string in JavaScript?

Well, keep reading because this article will show you how you can remove it easily and effectively.

Discover an expert approach to effectively remove non-alphanumeric characters in JavaScript with this comprehensive step-by-step guide.

Enhance your web development prowess and elevate the performance of your scripts.

What is non-alphanumeric characters?

Non-alphanumeric characters are those that are not letters or numbers.

They include symbols, punctuation marks, whitespace, and special characters that are not part of the alphabet or numeric system.

Examples of non-alphanumeric characters are “@” symbol, “&”, “$”, “#”, “%”, “*”, “.”, “/”, and many others.

While these characters serve various purposes like formatting or representing special characters, removing them is important when working with alphanumeric data to ensure consistency and compatibility.

How to remove non alphanumeric characters in javascript?

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.

Here’s the syntax:

str.replace();

It lets you find and replace specific parts of the string with ease.

Solution 1: Use string.replace()

For example, you can use str.replace(/[^a-z0-9]/gi, ”);.

This method replaces all non-alphanumeric characters in the string with nothing, effectively removing them.

const str = '!It&#source@%code*^(';

const replaced = str.replace(/[^a-z0-9]/gi, '');
console.log(replaced);

We added the “g” flag to match and replace all non-alphanumeric characters, not just the first one.

The “i” flag helps us ignore the difference between uppercase and lowercase letters during the matching process.

Output:

Itsourcecode

On the other hand, you use the following code which also uses the str.replace with call back function.

This solution is similar to the Solution above, but it uses a special function inside the replace() method.

It looks for any characters in the input string that are not letters or numbers (non-alphanumeric).

When a non-alphanumeric character is found, it is replaced with nothing, effectively removing it from the original string.

For example:

const inputString = "Hi, Welcome to @Itsource/code!";
const result = inputString.replace(/[^a-zA-Z0-9]/g, (match) => {
  return '';
});
console.log(result);

Output:

HiWelcometoItsourcecode

You can also use the following code:

const inputString = "Hi, Welcome to @Itsource/code!";
const result = inputString.replace(/[^a-zA-Z0-9]/g, "");
console.log(result);

This solution uses a regular expression /[^a-zA-Z0-9]/g to match any non-alphanumeric character in the input string.

The replace() method is then used to replace all the matched characters with an empty string, effectively removing them from the original string.

Output:

HiWelcometoItsourcecode

Solution 2: : Use the split() and join() methods with regular expressions

This method breaks down the input string into individual characters.

Then, it filters out only the characters that are alphanumeric using a regular expression /[a-zA-Z0-9]/.

Finally, it combines the filtered characters back into a single string.

const inputString = "Hi, Welcome to @Itsource/code!";
const result = inputString.split('').filter(char => /[a-zA-Z0-9]/.test(char)).join('');
console.log(result);

Output:

HiWelcometoItsourcecode

Solution 3: Use the ASCII Codes

In this solution, we use a for loop to examine each character in the input string.

By obtaining the ASCII code of each character using the charCodeAt() method, we determine if it falls within the range of alphanumeric characters.

Only the alphanumeric characters are added to a new string.

For example:

const inputString = "Hi, Welcome to @Itsource/code!";
let result = "";
for (let i = 0; i < inputString.length; i++) {
  const charCode = inputString.charCodeAt(i);
  if ((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
    result += inputString[i];
  }
}
console.log(result);

Output:

HiWelcometoItsourcecode

Solution 4: Use the \W special character

We can use the regex Metacharacter (\W) to remove all special characters, including spaces, from a string.

For example:

const str = '!It&#source@%code*^(';

const sample = str.replace(/\W/g, "");
console.log(sample);

Output:

Itsourcecode

To make your regular expression shorter and get rid of any non-alphanumeric characters in a string, you can use the special character \W.

Alternatively, you can use the following code, to remove non-alphanumeric characters from a string in JavaScript.

function removeNonAlphanumeric(string) {
  return string.replace(/\W/g, '');
}

console.log(removeNonAlphanumeric('It!(@s#o(u@r$ce/code')); 
console.log(removeNonAlphanumeric('I_T@s#o(*ur*ce(_code!'));

Output:

Itsourcecode
I_Tsource_code

Please be aware that the \W special character does not remove underscores from the string.

Why is it dominant to remove all non-alphanumeric characters in JavaScript?

It’s important to remove non-alphanumeric characters from string in JavaScript for several reasons.

By doing so, we ensure that the information remains consistent and in the desired format.

It also plays a vital role in validating inputs, enhancing security, and improving compatibility across different systems.

Moreover, removing these characters contributes to better readability and a smoother user experience, preventing errors and vulnerabilities in the process.

Conclusion

In conclusion, this article provides simple yet effective solutions for removing non-alphanumeric characters from a string in JavaScript.

By utilizing methods like String.replace(), regular expressions, and ASCII codes, these solutions ensure consistency, compatibility, and security in your code while improving readability and user experience.

We are hoping that this article provides you with enough information that helps you understand the remove non alphanumeric characters in JavaScript.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Quick step-by-step summary (click to expand)
  1. What is non-alphanumeric characters. Read the ‘What is non-alphanumeric characters?’ section for the details and code.
  2. How to remove non alphanumeric characters in javascript. Read the ‘How to remove non alphanumeric characters in javascript?’ section for the details and code.
  3. Why is it dominant to remove all non-alphanumeric characters in JavaScript. Read the ‘Why is it dominant to remove all non-alphanumeric characters in JavaScript?’ section for the details and code.
  4. Conclusion. Read the ‘Conclusion’ section for the details and code.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Caren Bautista


Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel
 · View all posts by Caren Bautista →

Leave a Comment