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

Summary of multiple methods to delete string spaces in javascript_javascript skills

WBOY
Release: 2016-05-16 17:48:59
Original
1096 people have browsed it

Copy code The code is as follows:

// 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
Copy code The code is as follows:

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
Copy code The code is as follows:

//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
Copy code The code is as follows:

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)
Copy code The code is as follows:

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;
}
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