Js write trim of function and the use of regular expressions

  • 2020-03-26 21:39:36
  • OfStack

1. Js itself has no trim function, but you can write one yourself

 
function trim(str) { 
var newStr = str.replace(/^s*$/g,'') 
retrun newStr; 
} 

2. Remove the white space at the left and right ends of the string. In vbscript, trim, ltrim or rtrim can be easily used. The following implementation USES regular expressions, which is efficient, and adds these three methods to the String object's built-in methods.

The method format is as follows :(str.trim();)
 
<script language="javascript"> 
String.prototype.trim=function(){ 
return this.replace(/(^s*)|(s*$)/g, ""); 
} 
String.prototype.ltrim=function(){ 
return this.replace(/(^s*)/g,""); 
} 
String.prototype.rtrim=function(){ 
return this.replace(/(s*$)/g,""); 
} 
</script> 
 The function can be written like this: (trim(str)) 
<script type="text/javascript"> 
function trim(str){ //Remove the left and right Spaces
return str.replace(/(^s*)|(s*$)/g, ""); 
} 
function ltrim(str){ //Remove the Spaces on the left
return str.replace(/(^s*)/g,""); 
} 
function rtrim(str){ //Delete the space on the right
return str.replace(/(s*$)/g,""); 
} 
</script> 


Related articles: