// Remove the leading space (left space) from the string
function LTrim(str){
var i;
for(i=0;iif(str.charAt(i)!=" ") break ;
}
str = str.substring(i,str.length);
return str;
}
// Remove the trailing space (right space) of the string
function RTrim(str){
var i;
for(i=str.length-1;i>=0;i--){
if(str.charAt(i)!=" ") break;
}
str = str.substring(0,i 1);
return str;
}
// Remove the leading and trailing spaces (left and right spaces) of the string
function Trim(str){
return LTrim(RTrim(str));
}
Delete all functions in the string
js delete string spaces function
function Jtrim(str)
{
var i = 0 ;
var len = str.length;
if ( str == "" ) return( str );
j = len -1;
flagbegin = true;
flagend = true;
while (( flagbegin == true) && (i< len))
{
if ( str.charAt(i) == " " )
{
i=i 1;
flagbegin=true;
}
else
{
flagbegin=false;
}
}
while ((flagend== true) && (j>= 0))
{
if (str.charAt(j)==" ")
{
j=j-1;
flagend=true;
}
else
{
flagend=false;
}
}
if ( i > j ) return ("");
trimstr = str.substring(i,j 1) ;
return trimstr;
}
The above methods do not use regular expressions. Let’s try using regular expressions.
Replace spaces with regular expressions
//Remove spaces in the middle of the string
String.prototype.Trim = function( ) {
return this.replace(/(^s*)|(s*$)/g, "");
}
//Remove spaces on the left side of the string
String.prototype .LTrim = function() {
return this.replace(/(^s*)/g, "");
}
//Remove spaces on the right side of the string
String.prototype. RTrim = function() {
return this.replace(/(s*$)/g, "");
}
Remove all spaces
var s = "asd ddd bbb sss";
var reg = /s/ g;
var ss = s.replace(reg, "");
alert(ss);
Remove all spaces in the string (including middle spaces, you need to set the second The parameters are: g)
function Trim(str,is_global )
{
var result;
result = str.replace(/(^s )|(s $)/g,"");
if(is_global.toLowerCase()==" g")
result = result.replace(/s/g,"");
return result;
}
Statement: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