To replace a space with an underscore in a paragraph using JavaScript, we can use the JavaScript String replace() method.
text.replace(/ /g, '_');
Let’s say we have the following HTML:
We will update the text: text with underscore
If we want to change the spaces in the span “text with underscore” and replace them with underscores, we will use the replace method in the following JavaScript code:
var text = document.getElementById("span1").textContent.replace(/ /g, '_');
document.getElementById("span1").innerHTML = text;
Which would result in the following:
We will update the text: text_with_underscore
Using JavaScript to Replace a Space with an Underscore with a Click
In this example, we will let the user input any text they want, and then replace any spaces in the text with underscores(_). We will then display the new text below. If there are no spaces in the text provided, no change will occur.
Here is the HTML setup.
Add text below with spaces.
Below is the JavaScript code which will take the user input using an onclick event and run the function below. The function will get the text using the getElementById method and textContent property, and use the replace() method on the text. We will then update the #results div using the textContent property.
Here is the JavaScript code:
function changeText() {
var userText = document.getElementById("userVal").value;
var replacedText = userText.replace(/ /g, '_');
document.getElementById("results").textContent = replacedText;
}
The final code and output for this example of how to replace spaces with underscores using JavaScript is below:
Code Output:
Add text below with spaces.
Full Code:
Add text below with spaces.
<script>
function changeText() {
var userText = document.getElementById("userVal").value;
var replacedText = userText.replace(/ /g, '_');
document.getElementById("results").textContent = replacedText;
}
</script>
Hopefully this article has been useful for you to understand how to use JavaScript to replace a space with an underscore.