Javascript trim string whitespace, with removing left and right spaces

Lionsure 2020-06-24 Original by the website

When dealing with characters, it is often necessary to remove the whitespace on the left of right of the characters or remove the spaces on the left and right at the same time; because javascript does not provide such function, you can only write it yourself. The following three functions use regular expressions to filter out whitespaces.

 

1. Javascript trim left and right spaces

String.prototype.trim = function(){
              return this.replace(/(^\s*)|(\s*$)/g, "");
       }

 

2. Javascript left trim string

String.prototype.l_trim = function(){
              return this.replace(/(^\s*)/g, "");
       }

 

3. Javascript right trim string

String.prototype.r_trim = function(){
              return this.replace(/(\s*$)/g, "");
       }

 

 

Examples of use are as follows:

<html>
       <head>
              <title>Javascript trim string whitespace, with removing left and right spaces</title>
              <script language="JavaScript" type="text/javascript">
                     String.prototype.trim = function(){
                            return this.replace(/(^\s*)|(\s*$)/g, "");
                     }
                     String.prototype.l_trim = function(){
                            return this.replace(/(^\s*)/g, "");
                     }
                     String.prototype.r_trim = function(){
                            return this.replace(/(\s*$)/g, "");
                     }
                     function RemoveSpace(){
                            var obj = document.getElementById("myname");

                     //Javascript trim left and right spaces
                            var temp = trim(obj.value);

                     //trim left whitespace
                            var l_temp = l_trim(obj.value);

                     //trim right whitespace
                            var r_temp = r_trim(obj.value);
                     }
              </script>
       </head>
       <body>
              <form id="form1"action="" method="post">
                     <div>
                            Name: <input type="text" id="myname" >
                            <input type="button" value="Submit" onclick="return RemoveSpace()" />
                     </div>
              </form>
       </body>
       </html>

 

If you want to use javascript to remove more spaces, please see the article "Javascript remove spaces (first and last, between words, all) with regular expression".