Try .replace(/ /g,"_");

Edit: or .split(' ').join('_') if you have an aversion to REs

Edit: John Resig said:

If you're searching and replacing through a string with a static search and a static replace it's faster to perform the action with .split("match").join("replace") - which seems counter-intuitive but it manages to work that way in most modern browsers. (There are changes going in place to grossly improve the performance of .replace(/match/g, "replace") in the next version of Firefox - so the previous statement won't be the case for long.)

Answer from Crescent Fresh on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › replacing-spaces-with-underscores-in-javascript
Replacing spaces with underscores in JavaScript - GeeksforGeeks
July 11, 2025 - Example 1: This example replaces all spaces(' ') with underscores("_") by using replace() method.
Discussions

How to replace all spaces present in a string with underscore using javascript? - Stack Overflow
I have a string with spaces separating words. I want to replace all the spaces in the string with underscore. Please tell me any small code for that because my solution is taking too much space. Ex... More on stackoverflow.com
🌐 stackoverflow.com
javascript - How to replace underscores with spaces? - Stack Overflow
I have an array with objects inside of it, a few of the objects contain an underscore in the string. Example: {"name": "My_name"} But I'm calling the name function in multiple ... More on stackoverflow.com
🌐 stackoverflow.com
How to replace underscores with spaces using a regex in Javascript - Stack Overflow
How can I replace underscores with spaces using a regex in Javascript? var ZZZ = "This_is_my_name"; More on stackoverflow.com
🌐 stackoverflow.com
javascript - Remove special symbols and extra spaces and replace with underscore using the replace method - Stack Overflow
I want to remove all special characters and spaces from a string and replace with an underscore. The string is var str = "hello world & hello universe"; I have this now which replaces only More on stackoverflow.com
🌐 stackoverflow.com
🌐
TutorialsPoint
tutorialspoint.com › article › replacing-spaces-with-underscores-in-javascript
Replacing spaces with underscores in JavaScript?
March 15, 2026 - <!DOCTYPE html> <html> <body> <h3>Replace Spaces with Underscores</h3> <p id="original"></p> <p id="result"></p> <button onclick="replaceSpaces()">Replace Spaces</button> <script> let sentence = "Welcome to Tutorials Point"; document.getElementById("original").innerHTML = "Original: " + sentence; function replaceSpaces() { let result = sentence.replace(/ /g, "_"); document.getElementById("result").innerHTML = "Result: " + result; } </script> </body> </html>
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-replace-spaces-with-underscores
How to Replace Spaces with Underscores in JavaScript | bobbyhadz
... Copied!function replaceSpa... // 👉️ bobby_hadz_com · The function takes a string as a parameter, replaces all spaces with underscores in the string and returns the result....
🌐
Code Highlights
code-hl.com › home › javascript › tutorials
5 Quick Methods to Replace Space with Underscore JavaScript | Code Highlights
August 18, 2024 - Regular expressions can be powerful for complex replacements. You can use them to target spaces specifically. ... Here, \s+ matches all whitespace characters, making it versatile for any spaces. You can also use Array.map() in combination with split() to replace spaces.
🌐
Delft Stack
delftstack.com › home › howto › javascript › javascript replace space with underscore
How to Replace Space With Underscore in JavaScript | Delft Stack
February 2, 2024 - We initialized a string containing multiple spaces in the above JavaScript source code. We used replace() method on that string with 2 arguments replace(" ","_"). It will find out the first " " (space) in the string and replace it with "_" ...
🌐
CodeSpeedy
codespeedy.com › home › replace spaces with underscores in javascript
Replace spaces with underscores in JavaScript - CodeSpeedy
November 2, 2022 - Learn how to replace spaces with underscores in JavaScript by using the replaceAll(), replace(), and split() and join() method.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 50643207 › how-to-replace-all-spaces-present-in-a-string-with-underscore-using-javascript › 50643241
How to replace all spaces present in a string with underscore using javascript? - Stack Overflow
I have a string with spaces separating words. I want to replace all the spaces in the string with underscore. Please tell me any small code for that because my solution is taking too much space. Ex...
🌐
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!
🌐
IQCode
iqcode.com › code › javascript › javascript-replace-space-by-underscore
javascript replace space by underscore Code Example
November 11, 2021 - var string = &quot;my name&quot;; string = string.replace(/ /g,&quot;_&quot;); //returns my_name
🌐
GitHub
gist.github.com › 2863c5c327711e6b0ad3
replace underscores with spaces and Capitalize - javascript · GitHub
replace underscores with spaces and Capitalize - javascript - gist:2863c5c327711e6b0ad3
🌐
TutorialsPoint
tutorialspoint.com › article › capitalize-a-word-and-replace-spaces-with-underscore-javascript
Capitalize a word and replace spaces with underscore - JavaScript?
March 15, 2026 - When executed, this code capitalizes the first letter of each word and replaces spaces with underscores. <!DOCTYPE html> <html> <body> <script> let sentence = "my favorite subject is javascript"; // Replace spaces with underscores, then capitalize first letter of each word let result = sentence.replace(/ /g, '_') .replace(/\b\w/g, function(match) { return match.toUpperCase(); }); document.write(result); </script> </body> </html>
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;
}

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

🌐
Codecademy
codecademy.com › forum_questions › 54208e6c80ff336390000948
How to substitute spaces for an underscore? | Codecademy
when "add" puts "Movie title:" title = gets.chomp.downcase sym_title = "" title_array = title.split(" ") title_array.each {|word| sym_title = sym_title + word + "_"} sym_title = sym_title.chomp('_') puts sym_title #This line is only here to check it's doing the right thing if movies[sym_title.to_sym].nil? puts "Movie rating (0-5)" rating = gets.chomp movies[sym_title.to_sym] = rating.to_i puts "The movie #{title} has been added with a rating of #{rating}." else puts "Movie is already in the database" end ... In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language. Beginner Friendly.Beginner Friendly4 Lessons4 Lessons ... Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
🌐
GitHub
github.com › bobbyhadz › javascript-replace-spaces-with-underscores
GitHub - bobbyhadz/javascript-replace-spaces-with-underscores: A repository for an article at https://bobbyhadz.com/blog/javascript-replace-spaces-with-underscores · GitHub
Clone the GitHub repository with the git clone command. Open your terminal in the project's root directory (right next to package.json). Install the node modules. ... To run the code, issue the npm start command. ... Alternatively, you can run the project in watch mode, so every time you save, the JavaScript server is restarted.
Author   bobbyhadz
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Chain regex to match underscore,space and caps - JavaScript - The freeCodeCamp Forum
April 26, 2019 - How can i chain regex to match caps,spaces and underscore in one regex?I can match spaces and underscore using: str.replace(/[\s,’_’]/g,’-’); · Part of me twitches whenever I see A-Z in a regex, what with all the world not being ASCII and all that. I guess we’ll have to wait a while ...
🌐
Adobe Support Community
community.adobe.com › home › app communities › indesign › questions › cs3: need script to replace spaces with underscores in paragraph and character style names
CS3: need script to replace spaces with underscores in paragraph and character style names | Community
November 25, 2009 - Just a Javascript oddity ... perhaps a hack that dates back to the grey mist of JS development ...) This should work -- but, rather then the above code, this is untested: ... The OR-group inbetween the square brackets contain all characters you want to replace with an underscore: the hyphen (this must be the first character in the group, else it will be interpreted as a range of the characters on either side!), the space, the forward slash (this one is 'special' inside Javascript's replace function, so I think it needs an escape with a backslash!), parentheses, a period (not sure if this needs escaping -- in plain GREP it's the any-character wildcard, but perhaps it looses its magic inside an OR-group), and finally ...