How to transform two or more spaces in a string in only one space? JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We have to write a JavaScript program that takes a variable user string through an input in HTML. Then through JavaScript the program should check for more than one consecutive spaces in the string.

And the program should replace all such instances of more than one consecutive spaces with only one space.

We can use a regular expression as the first parameter of replace. /\s{2,}/g to achieve the desired results. Let us write the code for this function −


 Live Demo

<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>REMOVE SPACES</title>
   function removeSpaces() {
      var textInput = insertText.value;
      var textInput = textInput.replace(/\s{2,}/g, " ");
      insertText.value = textInput;
<input type="text" id="insertText" value="containin extra space">
<button onclick="removeSpaces()">ok</button>

And the output will be −

After clicking OK,

Published on 23-Nov-2020 06:57:33