Your regular expression [^a-zA-Z0-9]\s/g says match any character that is not a number or letter followed by a space.

Remove the \s and you should get what you are after if you want a _ for every special character.

var newString = str.replace(/[^A-Z0-9]/ig, "_");

That will result in hello_world___hello_universe

If you want it to be single underscores use a + to match multiple

var newString = str.replace(/[^A-Z0-9]+/ig, "_");

That will result in hello_world_hello_universe

Answer from epascarello on Stack Overflow
Top answer
1 of 6
179

Your regular expression [^a-zA-Z0-9]\s/g says match any character that is not a number or letter followed by a space.

Remove the \s and you should get what you are after if you want a _ for every special character.

var newString = str.replace(/[^A-Z0-9]/ig, "_");

That will result in hello_world___hello_universe

If you want it to be single underscores use a + to match multiple

var newString = str.replace(/[^A-Z0-9]+/ig, "_");

That will result in hello_world_hello_universe

2 of 6
7

It was not asked precisely to remove accent (only special characters), but I needed to.

The solutions givens here works but they don’t remove accent: é, è, etc.

So, before doing epascarello’s solution, you can also do:

var newString = "développeur & intégrateur";

newString = replaceAccents(newString);
newString = newString.replace(/[^A-Z0-9]+/ig, "_");
alert(newString);

/**
 * Replaces all accented chars with regular ones
 */
function replaceAccents(str) {
  // Verifies if the String has accents and replace them
  if (str.search(/[\xC0-\xFF]/g) > -1) {
    str = str
      .replace(/[\xC0-\xC5]/g, "A")
      .replace(/[\xC6]/g, "AE")
      .replace(/[\xC7]/g, "C")
      .replace(/[\xC8-\xCB]/g, "E")
      .replace(/[\xCC-\xCF]/g, "I")
      .replace(/[\xD0]/g, "D")
      .replace(/[\xD1]/g, "N")
      .replace(/[\xD2-\xD6\xD8]/g, "O")
      .replace(/[\xD9-\xDC]/g, "U")
      .replace(/[\xDD]/g, "Y")
      .replace(/[\xDE]/g, "P")
      .replace(/[\xE0-\xE5]/g, "a")
      .replace(/[\xE6]/g, "ae")
      .replace(/[\xE7]/g, "c")
      .replace(/[\xE8-\xEB]/g, "e")
      .replace(/[\xEC-\xEF]/g, "i")
      .replace(/[\xF1]/g, "n")
      .replace(/[\xF2-\xF6\xF8]/g, "o")
      .replace(/[\xF9-\xFC]/g, "u")
      .replace(/[\xFE]/g, "p")
      .replace(/[\xFD\xFF]/g, "y");
  }

  return str;
}
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Source: https://gist.github.com/jonlabelle/5375315

🌐
ServiceNow Community
servicenow.com › community › developer-forum › using-regex-to-make-special-characters-disappear-except-when-it › m-p › 2574305
Using regex to make special characters disappear except when it is a dash. How do you do that?
May 31, 2023 - Correct. All the '-' signs are removed earlier within your step 1, since these are considered to be special characters. You can modify your step 1 and include '-' in your existing regex.
Discussions

I want to remove the special characters as well as extra spaces
Hi, I have one text file, which have lot of data. I want to remove the extra spaces and special characters from it. I have use, Regex.Replace( word1, " {2,}", " ") But there is no change in output. Please give suggestions. Thanks. @ClaytonM @palindrome @dmdixon75 More on forum.uipath.com
🌐 forum.uipath.com
14
1
March 27, 2019
Regular Expressions, How do you remove white space with special characters?
Tell us what’s happening: I tried \W but it didn’t work. I don’t want to pass the test with Hello, World! I need to do the “appropriate string methods” (pass the test with special characters). Your code so far let … More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
11
0
January 14, 2021
java - Remove spaces and special characters from string - Stack Overflow
The first line will remove the spaces. Then I am having trouble removing the parentheses. Android studio underlines the "(" and throws the error unclosed group. ... Sign up to request clarification or add additional context in comments. ... Amazing, the number of other verbose answers many of which did not work at all, your succinct answer did it ! Thanks ! 2017-10-04T14:26:15.2Z+00:00 ... Anyway your problem was caused by fact that some of characters in regex are special... More on stackoverflow.com
🌐 stackoverflow.com
June 27, 2014
One single Regex to Remove Special characters and multiple consecutive Spaces and Then Snake Case It - Stack Overflow
I need a one single regex that: removes special characters and numbers, removes multiple consecutive spaces and then snake case the input string. For example: Open Day - Explore the X-CAMPUS More on stackoverflow.com
🌐 stackoverflow.com
🌐
UiPath Community
forum.uipath.com › help
I want to remove the special characters as well as extra spaces - Help - UiPath Community Forum
March 27, 2019 - Hi, I have one text file, which have lot of data. I want to remove the extra spaces and special characters from it. I have use, Regex.Replace( word1, " {2,}", " ") But there is no change in output. Please give sugges…
🌐
RSWP Themes
rswpthemes.com › home › javascript tutorial › how to remove spaces and special characters from a string in javascript
How to Remove Spaces and Special Characters from a String in JavaScript
June 3, 2025 - How to remove spaces and special characters in JavaScript? Use the replace() method with a regular expression (regex) to remove spaces and special characters.
🌐
Text-Utils
text-utils.com › remove special characters
Remove Special Characters - Online Regex Tools | Text-Utils.com
September 6, 2025 - Keep numeric & spaces only: Remove all non-numeric & non-space characters from the text. Keep numeric-only: Remove all non-numeric characters from the text. Keep ASCII only: Remove all non-ASCII characters from the text. See the examples of usage below. ... Follow these steps to quickly delete unwanted symbols from the input. ... Have your text with unwanted characters ready. ... Paste your data or load the file into the input area. ... Click on the "Options" and select the desired character set you want to keep.
🌐
CodePen
codepen.io › MoyArt › pen › gjKLEj
JS - REGEX to remove spaces and special characters
HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug · Learn more · Versions
Find elsewhere
🌐
Ablebits
ablebits.com › ablebits blog › excel › regex › regex to remove certain characters or text in excel
Excel Regex to remove certain characters or text from strings
August 22, 2023 - To fix this, you can nest the above function into another one that replaces multiple spaces with a single space character. =RegExpReplace(RegExpReplace(A5,$A$2,""), " +", " ") Or just use the native TRIM function with the same effect: ... To delete all non-numeric characters from a string, you can use either this long formula or one of the very simple regexes listed below. ... Tip. If your goal is to remove text and spill the remaining numbers into separate cells or place them all in one cell separated with a specified delimiter, then use the RegExpExtract function as explained in How to extract numbers from string using regular expressions.
🌐
CodePal
codepal.ai › regex-generator › query › eVuSMMbI › regex-that-removes-special-characters-and-spaces
Regex for Removing Special Characters and Spaces - CodePal
Examples of strings that can be transformed using this regular expression are: - `Hello, World!` -> `HelloWorld` - `This is a test.` -> `Thisisatest` - `123-456-7890` -> `1234567890` Note that this regular expression may not be suitable for all use cases, as it removes all non-word characters and underscores. If you need to keep some special characters or spaces, you may need to modify the regular expression accordingly. ## References: - [Regex to remove special characters and spaces](https://stackoverflow.com/questions/9364400/remove-not-alphanumeric-characters-from-string-having-trouble-with-the-char)
🌐
freeCodeCamp
forum.freecodecamp.org › programming
Regular Expressions, How do you remove white space with special characters? - Programming - The freeCodeCamp Forum
January 14, 2021 - Tell us what’s happening: I tried \W but it didn’t work. I don’t want to pass the test with Hello, World! I need to do the “appropriate string methods” (pass the test with special characters). Your code so far let hello = " Hello, World! "; let wsRegex = /\b\w{5}\W+\s\D+\b/; // Change this line let result = hello.match(wsRegex); // Change this line console.log(result); Your browser information: User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0....
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-remove-special-characters-from-string
Remove special Characters from a String in JavaScript | bobbyhadz
We used the g (global) flag to ... of the regex in the string and not just the first occurrence. The square brackets [] part denotes a character class and the caret ^ symbol means "not the following characters". ... In its entirety, the regular expression matches all characters but lowercase and uppercase letters, digits and spaces...
🌐
ServiceNow Community
servicenow.com › community › developer-forum › regex-to-trim-white-space-and-special-characters-from-an-input › m-p › 2571230
Regex to trim white space and special characters from an input string before submission
May 29, 2023 - user_data .split('\n') // Break up the multi-row input into rows .map( function( row ){ // clean up each row row = row.trim(); // Remove the leading and trailing white spaces. row = row.replace( /[^\w\d &\-\(\)\.]/g, '' ); // Remove the characters that are not wanted. return row; } ) .join('\n'); // Put it all back together again. ... Thank you so much for your reply! The input is only a single-line text. In that case what will be my regex logic?
🌐
Coding Beauty
codingbeautydev.com › home › posts › how to remove special characters from a string in javascript
How to Remove Special Characters From a String in JavaScript
October 13, 2022 - So the regex matches any character is not a lowercase or uppercase letter, digit or space, and the replace() method returns a new string with all of these characters removed from the original string. The g (global) flag specifies that every occurrence of the pattern should be matched. If we don’t pass a global flag, only the first special ...
🌐
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 - Use replace() with regular expressions to efficiently remove special characters from strings in JavaScript.