- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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,
Advertisements