

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
<!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,
- Related Questions & Answers
- How to remove double or more spaces from a string in MySQL?
- How to increment one or more counters with JavaScript?
- Finding the only even or the only odd number in a string of space separated numbers in JavaScript
- How to reverse a string using only one variable in JavaScript
- Checking for Null or Empty or White Space Only String in Java.
- How to add two strings with a space in first string in JavaScript?
- Split Space Delimited String and Trim Extra Commas and Spaces in JavaScript?
- How to replace multiple spaces in a string using a single space using Java regex?
- Ways to select one or more pairs from two different sets in C++
- Match any string containing one or more p's with JavaScript RegExp.
- How to use spread operator to join two or more arrays in JavaScript?
- How to add two or more strings in MySQL?
- How to concatenate two or more vectors in R?
- Check if the String has only unicode digits or space in Java
- JavaScript Insert space after every two letters in string?
Advertisements