Question : Trim() in JavaScript using Regular Expression

Hi,

I have the following code for Trim(). But if a string contains more than one space between the words then i want to Trim it to one space. Can you please provide regular expression for that ?

Thanks

<html>

      <head>
      
            <script language=“JavaScript” type="text/javascript">

            String.prototype.Trim = function()
            {
                  return this.replace(/(^\s*)|(\s*$)/g, "");
            }
 
            // trim blank space at the beginning
            String.prototype.LTrim = function()
            {
                  return this.replace(/(^\s*)/g, "");
            }
 
            // trim blank space at the end
            String.prototype.RTrim = function()
            {
                  return this.replace(/(\s*$)/g, "");
            }

            function Test()
            {
                  var s = new String(" Hello,      world!  ");
                  s = s.Trim();
                  alert("#" + s + "#");
            }

            </script>

      </head>

      <body>
            <form name="form1">
                  <input type="button" name="button1" onclick="Test();" />
            </form>
      </body>

</html>

Answer : Trim() in JavaScript using Regular Expression

Check this:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
<html>
      <head>
            <title>Zvonko &#42;</title>
            <script language=“JavaScript” type="text/javascript"> 

            String.prototype.Trim = function() 
            { 
                  return this.replace(/(^\s*)|(\s*$)/g, "").replace(/\s+/g,' '); 
            } 
  
            // trim blank space at the beginning 
            String.prototype.LTrim = function() 
            { 
                  return this.replace(/(^\s*)/g, "").replace(/\s+/g,' '); 
            } 
  
            // trim blank space at the end 
            String.prototype.RTrim = function() 
            { 
                  return this.replace(/(\s*$)/g, "").replace(/\s+/g,' '); 
            } 

            function Test()
            {
                  var s = new String(" Hello,      world!  "); 
                  s = s.Trim(); 
                  alert("#" + s + "#"); 
            }

            </script>
      </head>
      <body>
            <form name="form1">
                  <input type="button" name="button1" value="Test" onclick="Test();" />
            </form>
      </body>
</html>
Random Solutions  
 
programming4us programming4us