Click here to Skip to main content
15,881,744 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to get rid the spaces in java script using regex.

I would appreciate a reply as soon as possible!

What I have tried:

var name = 'this is the test       case';
var nospaceString = name.replace(/\s+/g,'');
Posted
Updated 23-Oct-20 20:34pm

I'm not sure if you want all white spaces removed or to have words separated by 1 space. Below are 2 examples. And yes, I don't like RegEx, but was doing something similar the other day.

An example with no white space.
JavaScript
var name = "this is the test       case";
name = name.replace(/\s/g, '');
document.getElementById("test1").innerHTML = name;

An example with 1 space between words.
JavaScript
var name = "this is the test       case";
name = name.replace(/\s+/g, ' ').trim();
document.getElementById("test2").innerHTML = name;

Test in HTML.
HTML
<div id="test1"></div>
<div id="test2"></div>
 
Share this answer
 
Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx: Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx: Regexper[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900