Home > Web Front-end > JS Tutorial > How to remove whitespace characters on the left side, right side, whitespace characters on both sides, and all whitespace characters in a string

How to remove whitespace characters on the left side, right side, whitespace characters on both sides, and all whitespace characters in a string

一个新手
Release: 2017-10-12 09:59:31
Original
1746 people have browsed it

Sometimes we need to remove the whitespace characters from the string. The following is a method to remove the whitespace characters in various parts. It is actually a routine....

Remove the whitespace characters on the left side of the string


/*
* 去掉字符串开头空白符
* */

function removeBeginBlank(str) {
    return str.replace(/^\s*/g,"");    /* 返回替换后的字符串 */
}
var str = "    hahaha";   /* 要操作的字符串 */
removeBeginBlank(str);

/*
* 去掉字符串开头空白符结束
* */
Copy after login

Remove the whitespace on the right side of the string

/*
* 去掉字符串尾部空白字符
* */
    
function removeTrailBlank(str) {
    return str.replace(/\s*$/g,"");    /* 返回操作得到的字符串 */
}
var str = "hahah  ";   /* 要操作的字符串 */
removeTrailBlank(str);    
    
/*
* 去掉字符串尾部空白字符
* */
Copy after login

Remove the whitespace characters at both ends


/*
* 去掉两端空白字符
* */
    
function remove2PortBlank(str) {
    return str.replace(/^\s*|\s$/g,"");    /* 返回操作得到的字符串 */
}
var str = "hahah  ";   /* 要操作的字符串 */
removeTrailBlank(str);
    
/*
* 去掉两端空白字符
* */
Copy after login

Remove all whitespace characters


/*
* 去掉字符串所有空白符
* */
    
function removeAllBlank(str) {
    return str.replace(/\s*/g,"");    /* 返回操作得到的字符串 */
}
var str = "    hah   aha   ";   /* 要操作的字符串 */
removeAllBlank(str);

/*
* 去掉字符串所有空白符结束
* */
Copy after login

The above is the detailed content of How to remove whitespace characters on the left side, right side, whitespace characters on both sides, and all whitespace characters in a string. For more information, please follow other related articles on 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