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


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 −

Example

 Live Demo

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

And the output will be −

After clicking OK,

Updated on: 23-Nov-2020

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements