How to use JS to remove spaces before and after a string or remove all spaces

1. Remove all spaces before and after the string:

code show as below:

function Trim(str)
 {
  return str.replace(/(^\s*)|(\s*$)/g, ""); 
}
View Code

 

    illustrate:

    If you use jQuery to use the $.trim(str) method directly, str represents a string with all spaces before and after it removed.

 2. Remove all spaces in the string (including intermediate spaces, you need to set the second parameter to: g)

code show as below:

 function Trim(str,is_global)
  {
   var result;
   result = str.replace(/(^\s+)|(\s+$)/g,"");
   if(is_global.toLowerCase()=="g")
   {
    result = result.replace(/\s/g,"");
    }
   return result;
}
View Code

 

3. Most browsers now basically support the trim function of strings, but in order to be compatible with unsupported browsers, we'd better add the following code to the Js file (if you don't need to clear line breaks, please delete the \n system Tab delete \t):

if (!String.prototype.trim) {
 
 /*---------------------------------------
  * Clear the spaces at both ends of the string, including newlines and tabs
  *---------------------------------------*/
 String.prototype.trim = function () { 
  return this.triml().trimr(); 
 }
 
 /*----------------------------------------
  * Clear the spaces on the left side of the string, including newlines, tabs
  * ---------------------------------------*/
 String.prototype.triml = function () {
  return this.replace(/^[\s\n\t]+/g, "");
 }
 
 /*----------------------------------------
  * Clear the spaces on the right side of the string, including newlines, tabs
  *----------------------------------------*/
 String.prototype.trimr = function () {
  return this.replace(/[\s\n\t]+$/g, "");
 }
}
View Code

 

If you only need the trim function, you can just write one:

if (!String.prototype.trim){
 
 /*---------------------------------------
  * Clear the spaces at both ends of the string, including newlines and tabs
  *---------------------------------------*/
 String.prototype.trim = function () { 
  return this.replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, "");
 }
  
}
View Code

 

Use code:

    
var str = " abcd ".trim();
View Code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325019937&siteId=291194637