How can we remove spaces when users enter spaces during project registration?
Below is my frequently used js to share with you:
First: Replacement of cyclic check
[Javascript]
Copy codeThe Code is as follows:
// For the user to call
Function trim (s ){
Return trimRight (trimLeft (s ));
}
// Remove the left blank
Function trimLeft (s ){
If (s = null ){
Return "";
}
Var whitespace = new String ("\ t \ n \ r ");
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 www.jb51.net on the right.
Function trimRight (s ){
If (s = null) return "";
Var whitespace = new String ("\ t \ n \ r ");
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;
}
Type 2: Regular Expression replacement
[Javascript]
Copy codeThe Code is as follows:
<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>
Third: Use jquery
[Javascript]
Copy codeThe Code is as follows:
$. Trim (str)
The internal implementation of jquery is:
[Javascript]
Copy codeThe Code is as follows:
Function trim (str ){
Return str. replace (/^ (\ s | \ u00A0) +/, ''). replace (/(\ s | \ u00A0) + $ /,'');
}
Type 4: Use motools
[Javascript]
Copy codeThe Code is as follows:
Function trim (str ){
Return str. replace (/^ (\ s | \ xA0) + | (\ s | \ xA0) + $/g ,'');
}
Method 5: Crop a string
[Javascript]
Copy codeThe Code is as follows:
Function trim (str ){
Str = str. replace (/^ (\ s | \ u00A0) + /,'');
For (var I = str. length-1; I> = 0; I --){
If (/\ S/. test (str. charAt (I ))){
Str = str. substring (0, I + 1 );
Break;
}
}
Return str;
}
After testing, the fifth method has the highest validity rate when processing long strings..
Copy codeThe Code is as follows:
<Script type = "text/JavaScript">
// Remove Spaces
Function SystemTrim (str ){
Var regExp =/(^ \ s *) | (\ s * $ )/;
Return str. replace (regExp ,"");
}
// Call
Function add ()
{
Var ownername = document. form1.ownername. value;
If (SystemTrim (ownername) = "")
{
Alert ("enter your name! ");
Return;
}
}
<Script>