Home > Web Front-end > JS Tutorial > body text

JS regular expression to remove spaces and newlines (recommended)

高洛峰
Release: 2016-12-26 16:53:41
Original
1258 people have browsed it

When I was programming a few days ago, I encountered a problem that took me a long time to solve. It really drove me crazy! Putting a string into setTimeout cannot execute the method. Later, I found out that it was because there was an extra newline after the string. I couldn't see it unless I looked carefully. I just used regular expressions to remove the newline.

//去除空格 
String.prototype.Trim = function() { 
return this.replace(/\s+/g, ""); 
} 
 
//去除换行 
function ClearBr(key) { 
key = key.replace(/<\/?.+?>/g,""); 
key = key.replace(/[\r\n]/g, ""); 
return key; 
} 
 
//去除左侧空格 
function LTrim(str) { 
return str.replace(/^\s*/g,""); 
} 
 
//去右空格 
function RTrim(str) { 
return str.replace(/\s*$/g,""); 
} 
 
//去掉字符串两端的空格 
function trim(str) { 
return str.replace(/(^\s*)|(\s*$)/g, ""); 
} 
 
//去除字符串中间空格 
function CTim(str) { 
return str.replace(/\s/g,&#39;&#39;); 
} 
 
//是否为由数字组成的字符串 
function is_digitals(str) { 
var reg=/^[0-9]*$/; //匹配整数 
return reg.test(str); 
}
Copy after login

Now I find that I like to use regular expressions more and more, haha! It is relatively simple and intuitive. Of course, the prerequisite is that you are familiar with regular expressions. I also tried to write this JS method to delete newlines, and it really worked for me!

The above JS regular expression for removing spaces and newlines (recommended) is all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.

For more JS regular expressions to remove spaces and newlines (recommended), please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template