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

🌐
C# Corner
c-sharpcorner.com › article › javascript-replace-spaces
JavaScript Replace Spaces
December 27, 2023 - When spaces and special characters are to be replaced by a common symbol like an underscore ( _ ), the replace() method becomes your trusted option. const stringWithSpaces = "Replace!
🌐
Metring
ricardometring.com › javascript-replace-special-characters
JavaScript: Replacing Special Characters - The Clean Way
But maybe you also need to replace unnecessary hyphens, as in the case of "This is a sentence!!!" turning into "This-is-a-sentence---". Here's a complete function that removes accents, replaces special characters with hyphens, also removing additional hyphens: const replaceSpecialChars = (str) => { return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '') // Remove accents .replace(/([^\w]+|\s+)/g, '-') // Replace space and other characters by hyphen .replace(/\-\-+/g, '-') // Replaces multiple hyphens by one hyphen .replace(/(^-+|-+$)/g, ''); // Remove extra hyphens from beginning or end of the string } console.log(replaceSpecialChars('This is a sentence!!!'));
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript replace all word | space, comma | special characters
How to JavaScript replace all Word | Space, Comma | Special Character
May 15, 2021 - <!DOCTYPE html> <html> <script> var string = 'EyeHunts Tutorial JS'; var newstring = string.replace(/JS/, 'Javascript'); document.write(newstring); </script> <body> </body> </html> ... The best way is to use regular expression with g (global) flag. ...
🌐
CodePen
codepen.io › MoyArt › pen › gjKLEj
JS - REGEX to remove spaces and special characters
Minimize JavaScript Editor · Fold All · Unfold All · const word = 'HI THERE!!!' console.log(word.replace(/[^\w]/g, "")) ! 999px · Clear · Ctrl Ctrl Space Autocomplete · F Find · G Find Next · ⇧ G Find Previous · ⇧ Opt F Find & Replace ...
Find elsewhere
🌐
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 - Regex is often the fastest for complex patterns. For simple tasks like removing spaces, string methods like trim() or split()/join() can be sufficient and more readable. Cleaning strings in JavaScript is straightforward with regex or string methods.
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-remove-special-characters-from-string
Remove special Characters from a String in JavaScript | bobbyhadz
We used the plus + symbol to match one or more occurrences of a space and replaced multiple spaces with a single space. An alternative approach to using the caret ^ symbol to specify the characters we want to keep is to specify the special ...
🌐
TutorialsPoint
tutorialspoint.com › article › javascript-regex-how-to-replace-special-characters
JavaScript regex - How to replace special characters?
In the following example, we are running the script to replace all the special characters using replace(). <!DOCTYPE html> <html> <body style="background-color:#ABEBC6"> <script> var statement = "We#@lcome!! To! The@ Tutorials$Point%"; var result = statement.replace(/[^a-zA-Z ]/g, ""); document.write(result); </script> </body> </html> ... Considering the following example, where we are running the script to replace special characters using replace().
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-replace-spaces-with-underscores
How to Replace Spaces with Underscores in JavaScript | bobbyhadz
Copied!const str = 'bobby\nhadz\tcom abc'; const strUnderscores = str.replace(/\s/g, '_'); console.log(strUnderscores); // 👉️ bobby_hadz_com_abc · The \s special character matches spaces, tabs and newlines.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › replacing-spaces-with-underscores-in-javascript
Replacing spaces with underscores in JavaScript - GeeksforGeeks
July 11, 2025 - It holds the integer that specifies the number of splits, items beyond the split limit will be excluded from the array. Example 1: This example replaces all spaces(' ') with underscores("_") by using replace() method.