JS Regular Expression of Recommendation for Removing Spaces and Line Breaks

  • 2021-06-28 10:47:18
  • OfStack

When I was programming the other day, I encountered a problem that I had to solve for a long time. It really made me mad!Putting a string into setTimeout does not execute the method, but later found that because there is one more line break behind the string, it cannot be seen carefully. Use regular expressions to remove the line breaks.


// Remove whitespace  
String.prototype.Trim = function() { 
return this.replace(/\s+/g, ""); 
} 

// Remove line breaks  
function ClearBr(key) { 
key = key.replace(/<\/?.+?>/g,""); 
key = key.replace(/[\r\n]/g, ""); 
return key; 
} 

// Remove left space  
function LTrim(str) { 
return str.replace(/^\s*/g,""); 
} 

// Remove right space  
function RTrim(str) { 
return str.replace(/\s*$/g,""); 
} 

// Remove spaces at both ends of a string  
function trim(str) { 
return str.replace(/(^\s*)|(\s*$)/g, ""); 
} 

// Remove spaces in the middle of strings  
function CTim(str) { 
return str.replace(/\s/g,''); 
} 

// Is it a string of numbers  
function is_digitals(str) { 
var reg=/^[0-9]*$/; // Match Integer  
return reg.test(str); 
}

Now I find myself more and more fond of using regular expressions, huh!It is simple and intuitive.Of course, the precondition is that you are familiar with regular expressions.I also tried to write this JS method to delete line breaks, which really made me realize!


Related articles: