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

js trim function, space removal function and regular collection_javascript skills

WBOY
Release: 2016-05-16 18:41:34
Original
1124 people have browsed it

But if the project does not use a framework such as jQuery, js itself does not have such a function, and we have to write such a function ourselves. The following is the specific implementation of the function:

Copy the code The code is as follows:

//For users to call
function trim(s){
return trimRight(trimLeft(s));
}
//Remove the left whitespace
function trimLeft(s){
if(s == null) {
return "";
}
var whitespace = new String(" tnr");
var str = new String(s);
if (whitespace.indexOf(str.charAt(0)) != -1) {
var j=0, i = str.length;
while (j < i && whitespace.indexOf(str.charAt(j)) != -1){
j ;
}
str = str.substring (j, i);
}
return str;
}
//Remove the blank space on the right
function trimRight(s){
if(s == null) return " ";
var whitespace = new String(" tnr");
var str = new String(s);
if (whitespace.indexOf(str.charAt(str.length-1)) != -1){
var i = str.length - 1;
while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1){
i-- ;
}
str = str.substring(0, i 1);
}
return str;
}

When using, just call the trim function That’s it.
The following is the implementation method using regular expressions:
Copy the code The code is as follows:

< ;SCRIPT LANGUAGE="JavaScript">








Because of the editor problem, the spaces have been replaced in the above code, so Please pay attention to adding spaces and test.
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