Home >Web Front-end >JS Tutorial >How to use JS to remove spaces before and after a string or remove all spaces
This article mainly introduces the usage of JS to remove spaces before and after a string or remove all spaces. Friends who need it can refer to
1. Remove all spaces before and after a string:
The code is as follows:
function Trim(str) { return str.replace(/(^\s*)|(\s*$)/g, ""); }
Description:
If you use jQuery, just use the $.trim(str) method directly, str represents a string to remove all leading and trailing spaces.
2. Remove all spaces in the string (including intermediate spaces, you need to set the second parameter to: g)
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; }
3. Most browsers now basically support the trim function of strings. However, in order to be compatible with browsers that do not support it, we’d better add the following to the Js file. Code (if you don’t need to remove line breaks, please delete \n and delete tabs \t):
if (!String.prototype.trim) { /*--------------------------------------- * 清除字符串两端空格,包含换行符、制表符 *---------------------------------------*/ String.prototype.trim = function () { return this.triml().trimr(); } /*---------------------------------------- * 清除字符串左侧空格,包含换行符、制表符 * ---------------------------------------*/ String.prototype.triml = function () { return this.replace(/^[\s\n\t]+/g, ""); } /*---------------------------------------- * 清除字符串右侧空格,包含换行符、制表符 *----------------------------------------*/ String.prototype.trimr = function () { return this.replace(/[\s\n\t]+$/g, ""); } }
If you only need the trim function, you can just write one :
if (!String.prototype.trim){ /*--------------------------------------- * 清除字符串两端空格,包含换行符、制表符 *---------------------------------------*/ String.prototype.trim = function () { return this.replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, ""); } }
Use code:
var str = " abcd ".trim();
Related recommendations:
Detailed explanation of JS removal of all commas in a string
JS method of removing punctuation marks at the end of a string
The above is the detailed content of How to use JS to remove spaces before and after a string or remove all spaces. For more information, please follow other related articles on the PHP Chinese website!