Remove spaces in string using regex - Javascript RegExp

Javascript examples for RegExp:Match Space

Description

Remove spaces in string using regex

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){//www . j a v a 2 s  . co  m
function removeSpace(string) {
    return string.replace(/\s*([^\s]+\s?)\s*/g, '$1');
}
console.log("|" + removeSpace(" My      name         is        Joe      ") + "|");
console.log("|" + removeSpace(" My           name is            Joe") + "|");
console.log("|" + removeSpace("     My           name is            Joe") + "|");
    }

      </script> 
   </head> 
   <body>  
   </body>
</html>

Related Tutorials