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
๐ŸŒ
Mefancy
mefancy.com โ€บ textchange โ€บ replace-space-underscore
Replace Spaces with Underscores (and more) - Online Text Tool | MeFancy
Free online tool to replace spaces with underscores, hyphens, or custom characters. Also converts underscores/hyphens back to spaces. Fast, secure, and client-side.
๐ŸŒ
PhraseFix
phrasefix.com โ€บ tools โ€บ replace-spaces-with-underscores
Whitespace to Underscore Tool - PhraseFix
Free online tool that replaces spaces/whitespace with underscores instantly. Simply enter the text and the online tool convert spaces to underscores.
People also ask

Why Use an Underscore Remover?
Underscores are commonly used in file names, variable names, and technical documents, but they can make text look cluttered and difficult to read when you want to present it in a more user-friendly format. Our Underscore Remover tool instantly transforms text by replacing all underscores with spaces, making it more readable and presentable. ยท This tool is perfect for cleaning up file names, converting technical documentation to readable format, or preparing text for presentations. Simply paste your text with underscores, and get clean, space-separated text instantly. It's a simple but essentia
๐ŸŒ
convertcase.net
convertcase.net โ€บ convert case โ€บ remove underscores
Remove Underscores | Replace with Spaces | Convert Case
How Does the Remove Underscores Tool Work?
Our Remove Underscores tool uses a simple but effective approach: it scans through your input text and replaces every underscore character with a regular space character. The conversion happens in real-time as you type, providing instant feedback and allowing you to see the transformation immediately. ยท The tool preserves all other formatting and characters in your text, only targeting underscores for replacement. This ensures that your content maintains its original structure while becoming more readable and user-friendly.
๐ŸŒ
convertcase.net
convertcase.net โ€บ convert case โ€บ remove underscores
Remove Underscores | Replace with Spaces | Convert Case
Why You May Not Want Underscores in Your Text
While underscores serve important technical purposes, they can significantly impact readability and user experience when presenting information to general audiences. Underscores create visual clutter and make text harder to scan quickly, as the human brain naturally expects spaces between words for optimal reading comprehension. ยท In professional presentations, documentation for end users, or marketing materials, underscores can make content appear overly technical or unpolished. They can also cause accessibility issues for screen readers, which may not properly interpret underscores as word s
๐ŸŒ
convertcase.net
convertcase.net โ€บ convert case โ€บ remove underscores
Remove Underscores | Replace with Spaces | Convert Case
๐ŸŒ
ToggleCase
togglecase.com โ€บ convert_to_underscored
Underscored Text Generator - Free Online Text Conversion
ToggleCase cuts out all the hassle of manually replacing spaces with underscores to create Embedded Underscore text. Simply type or paste any words you want to convert into the form below, and hit the magic Underscored Text button. Then just copy and paste your Embedded Underscore text to use!
๐ŸŒ
Online Text Tools
onlinetexttools.com โ€บ replace-text-spaces
Replace Spaces in Text โ€“ Online Text Tools
This can be done using the "Replace Clusters of Spaces" option. For example, if you have the text "dream big" (with three repeated spaces), then with the option turned off you will get "dream___big" (underscore for each space), and with the option turned on you will get "dream_big" (all three spaces replaced with a single underscore).
๐ŸŒ
Myfreeonlinetools
myfreeonlinetools.com โ€บ remove-all-white-space-with-undersocre-&-hypen-dash
Space Replace with Hyphen or Undersocre | myfreeonlinetools
Myfreeonlinetools provides an easy online tool that can remove space and replace them with commas, underscore, dash, and change case in strings, lines or paragrah.
๐ŸŒ
PhraseFix
phrasefix.com โ€บ tools โ€บ replace-spaces
Replace All Spaces Tools - PhraseFix
Use this tool to replace any horizontal whitespace with a comma, underscore, period, dash, or any text you desire. Replace Spaces Example
๐ŸŒ
Bubble
forum.bubble.io โ€บ need help
How to convert all the spaces in an input to underscores - Need help - Bubble Forum
February 21, 2023 - Here for this input i want to covert all the spaces to underscores Kindly guide
Find elsewhere
๐ŸŒ
Convert Case
convertcase.net โ€บ convert case โ€บ remove underscores
Remove Underscores | Replace with Spaces | Convert Case
The Remove Underscores tool replaces every underscore character in your text with a regular space, instantly converting technical or system-generated names into readable, human-friendly text.
๐ŸŒ
Avantix Learning
avantixlearning.ca โ€บ home โ€บ how to replace spaces in excel with underscores (_), dashes (-) or other values
How to Replace Spaces in Excel with Underscores (_), Dashes (-) or Other Values
April 13, 2022 - In Excel, you can replace spaces in text strings with underscores, dashes or other values using Find and Replace, by creating a formula or by using Flash Fill. ... Avantix Learning courses are offered online in virtual classroom format or as in-person classroom training.
๐ŸŒ
Text Mechanic
textmechanic.com โ€บ replace-underscores-with-spaces
Replace Underscores with Spaces - Text Mechanic
November 15, 2018 - Replace Underscores with Spaces ยท Privacy Policy Fulfillment Policy ยท Limit of 4 free tasks per hour exceeded! Get unlimited access with TextMechanic Pro or take a break for ยท Get TextMechanic Pro
๐ŸŒ
Code Highlights
code-hl.com โ€บ home โ€บ javascript โ€บ tutorials
5 Quick Methods to Replace Space with Underscore JavaScript | Code Highlights
August 18, 2024 - This code uses the replace method with a regular expression to find spaces and replace them with underscores.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ replacing-spaces-with-underscores-in-javascript
Replacing spaces with underscores in JavaScript?
January 18, 2023 - This method splits the string at each space, creating an array of words, then joins them with underscores. URL Slugs: Converting page titles to URL-friendly formats ยท File Names: Creating valid file names from user input ยท Database Fields: Formatting data for database storage ยท CSS Classes: Converting text to valid CSS class names ยท For modern applications, replaceAll() offers the cleanest syntax for simple replacements.
Top answer
1 of 3
5

Perfect candidate for a token cycle. EDITED to add lowercasing, as requested.

\documentclass{article}
\usepackage{tokcycle}
\Characterdirective{\addcytoks[x]{\explowerchar{#1}}}
\Spacedirective{\addcytoks{\textunderscore\allowbreak}}
\def\explowerchar#1{%
  \ifcase\numexpr`#1-`A\relax
   a\or b\or c\or d\or e\or f\or g\or h\or i\or j\or k\or l\or m\or
   n\or o\or p\or q\or r\or s\or t\or u\or v\or w\or x\or y\or z\else
   #1\fi
}

\newcommand{\questionsection}{Game of  rolling   dice, plus this should
  allow line breaks as well.  Let us see if it does}
\newcommand{\questionsectionfiltered}{\expandafter\tokencyclexpress
  \questionsection\endtokencyclexpress}

\begin{document}
    \questionsectionfiltered
\end{document}

2 of 3
7

You can use expl3 that's more robust than xstring (and more flexible).

\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\filter}{m}
 {
  \tabraham_filter:n { #1 }
 }

\tl_new:N \l__tabraham_filter_text_tl

\cs_new_protected:Nn \tabraham_filter:n
 {
  % set the tl variable to the lowercased version of the input
  \tl_set:Nx \l__tabraham_filter_text_tl { \text_lowercase:n { #1 } }
  % replace spaces with underscores
  \tl_replace_all:Nnn \l__tabraham_filter_text_tl { ~ } { \_ }
  % deliver the result
  \tl_use:N \l__tabraham_filter_text_tl
 }

\ExplSyntaxOff

\newcommand{\questionsection}{Game of  rolling   dice}

\begin{document}

\filter{\questionsection}

\filter{Game of  rolling   dice}

\end{document}

You may want to define a filtered version of some token list, so when using it you don't have to repeat the whole process.

\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\filter}{m}
 {
  \tabraham_filter:nn { #1 } { \tl_use:N }
 }
\NewDocumentCommand{\newfilteredcommand}{mm}
 {
  \tl_if_exist:NF #1
   {
    You~don't~want~to~silently~redefine~something,~do~you?
   }
   {
    \tl_new:N #1
    \tabraham_filter:nn { #2 } { \tl_set_eq:NN #1 }
   }
 }

\tl_new:N \l__tabraham_filter_text_tl

\cs_new_protected:Nn \tabraham_filter:nn
 {
  \tl_set:Nx \l__tabraham_filter_text_tl { \text_lowercase:n { #1 } }
  \tl_replace_all:Nnn \l__tabraham_filter_text_tl { ~ } { \_ }
  #2 \l__tabraham_filter_text_tl
 }

\ExplSyntaxOff

\newcommand{\questionsection}{Game of  rolling   dice}
\newfilteredcommand{\questionsectionfiltered}{\questionsection}

\begin{document}

\filter{\questionsection}

\filter{Game of  rolling   dice}

\questionsectionfiltered

\texttt{\meaning\questionsectionfiltered}

\end{document}

The last line is to show that \questionsectionfiltered is what's expected.

๐ŸŒ
Statology
statology.org โ€บ home โ€บ how to replace space with underscore in excel
How to Replace Space with Underscore in Excel
August 17, 2023 - First, highlight the cell range A2:A11. Then type Ctrl + H to bring up the Find and Replace feature in Excel. Then type a single space in the Find what box and type a single underscore in the Replace with box.
๐ŸŒ
Tutor Python
tutorpython.com โ€บ python-replace-space-with-underscore
Python Replace Space with Underscore - Tutor Python
October 19, 2023 - By invoking the replace() method, a new string is generated, where all occurrences of the specified substring are substituted accordingly. This method provides a straightforward and intuitive approach for replacing specific substrings within ...
๐ŸŒ
The Bricks
thebricks.com โ€บ home โ€บ resources โ€บ how to replace spaces with underscores in excel
How to Replace Spaces with Underscores in Excel - Bricks
February 12, 2025 - Don't type the word "space," just a literal space character. In the "Replace with:" field, type an underscore ( _ ).
๐ŸŒ
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