如何在 JavaScript 中修剪字符串?也就是说,如何在 JavaScript 中删除字符串开头和结尾的所有空格?
20 回答
自 IE9+ 以来的所有浏览器都有trim()
字符串方法:
" \n test \n ".trim(); // returns "test" here
对于那些不支持的浏览器trim()
,你可以使用MDN的这个 polyfill :
if (!String.prototype.trim) {
(function() {
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function() {
return this.replace(rtrim, '');
};
})();
}
也就是说,如果 using jQuery
,$.trim(str)
也可用并处理 undefined/null。
看到这个:
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};
String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
如果您已经在使用该框架,那么来自jQuery的修剪会很方便。
$.trim(' your string ');
我倾向于经常使用 jQuery,所以用它修剪字符串对我来说很自然。但是有可能对 jQuery 有强烈反对吗?:)
虽然上面有一堆正确的答案,但应该注意的是,JavaScript 中的对象从ECMAScript 5String
开始就有一个本地.trim()
方法。因此,理想情况下,任何对 trim 方法进行原型设计的尝试都应该首先检查它是否已经存在。
if(!String.prototype.trim){
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g,'');
};
}
原生添加于: JavaScript 1.8.1 / ECMAScript 5
因此支持:
火狐:3.5+
野生动物园:5+
Internet Explorer:IE9+(仅限标准模式!)http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more .aspx
铬:5+
歌剧:10.5+
ECMAScript 5 支持表: http: //kangax.github.com/es5-compat-table/
有很多实现可以使用。最明显的似乎是这样的:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
" foo bar ".trim(); // "foo bar"
简单版在这里JavaScript trim 的通用功能是什么?
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}
我知道这个问题三年前就被问过了。现在,String.trim()
是在 JavaScript 中原生添加的。例如,您可以直接修剪如下,
document.getElementById("id").value.trim();
如果您使用的是 jQuery,请使用该jQuery.trim()
函数。例如:
if( jQuery.trim(StringVariable) == '')
Flagrant Badassery有 11 种带有基准信息的不同装饰:
http://blog.stevenlevithan.com/archives/faster-trim-javascript
毫不奇怪,基于正则表达式的速度比传统循环慢。
这是我个人的。这段代码很旧!我为 JavaScript1.1 和 Netscape 3 编写了它,从那以后它只做了轻微的更新。(原来用的String.charAt)
/**
* Trim string. Actually trims all control characters.
* Ignores fancy Unicode spaces. Forces to string.
*/
function trim(str) {
str = str.toString();
var begin = 0;
var end = str.length - 1;
while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; }
while (end > begin && str.charCodeAt(end) < 33) { --end; }
return str.substr(begin, end - begin + 1);
}
使用原生 JavaScript 方法:String.trimLeft()
、String.trimRight()
和String.trim()
.
String.trim()
IE9+ 和所有其他主流浏览器都支持:
' Hello '.trim() //-> 'Hello'
String.trimLeft()
并且String.trimRight()
是非标准的,但在除 IE 之外的所有主要浏览器中都支持
' Hello '.trimLeft() //-> 'Hello '
' Hello '.trimRight() //-> ' Hello'
IE 支持很容易使用 polyfill,但是:
if (!''.trimLeft) {
String.prototype.trimLeft = function() {
return this.replace(/^\s+/,'');
};
String.prototype.trimRight = function() {
return this.replace(/\s+$/,'');
};
if (!''.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
}
String.prototype.trim = String.prototype.trim || function () {
return this.replace(/^\s+|\s+$/g, "");
};
String.prototype.trimLeft = String.prototype.trimLeft || function () {
return this.replace(/^\s+/, "");
};
String.prototype.trimRight = String.prototype.trimRight || function () {
return this.replace(/\s+$/, "");
};
String.prototype.trimFull = String.prototype.trimFull || function () {
return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, " ");
};
无耻地从马特杜雷格那里偷走。
从Angular js项目中修剪代码
var trim = (function() {
// if a reference is a `String`.
function isString(value){
return typeof value == 'string';
}
// native trim is way faster: http://jsperf.com/angular-trim-test
// but IE doesn't have it... :-(
// TODO: we should move this into IE/ES5 polyfill
if (!String.prototype.trim) {
return function(value) {
return isString(value) ?
value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
};
}
return function(value) {
return isString(value) ? value.trim() : value;
};
})();
并将其称为trim(" hello ")
使用简单的代码
var str = " Hello World! ";
alert(str.trim());
浏览器支持
Feature Chrome Firefox Internet Explorer Opera Safari Edge
Basic support (Yes) 3.5 9 10.5 5 ?
对于旧浏览器添加原型
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
这是一个非常简单的方法:
function removeSpaces(string){
return string.split(' ').join('');
}
我有一个使用修剪的库。所以通过使用以下代码解决了它。
String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };
早在 2008 年,当 .trim() 函数在 JS 中不可用时,我已经为 trim 编写了这个函数。一些较旧的浏览器仍然不支持 .trim() 函数,我希望这个函数可以帮助某人。
修剪功能
function trim(str)
{
var startpatt = /^\s/;
var endpatt = /\s$/;
while(str.search(startpatt) == 0)
str = str.substring(1, str.length);
while(str.search(endpatt) == str.length-1)
str = str.substring(0, str.length-1);
return str;
}
解释:函数 trim() 接受一个字符串对象并删除所有开头和结尾的空格(空格、制表符和换行符)并返回修剪后的字符串。您可以使用此功能修剪表单输入以确保发送有效数据。
以如下方式调用该函数为例。
form.elements[i].value = trim(form.elements[i].value);
你可以使用普通的 JavaScript 来做到这一点:
function trimString(str, maxLen) {
if (str.length <= maxLen) {
return str;
}
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}
// Let's test it
sentenceOne = "too short";
sentencetwo = "more than the max length";
console.log(trimString(sentenceOne, 15));
console.log(trimString(sentencetwo, 15));
不知道这里可以隐藏什么错误,但我使用这个:
var some_string_with_extra_spaces=" goes here "
console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])
或者这个,如果文本包含输入:
console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])
另一个尝试:
console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])
这是在 TypeScript 中:
var trim: (input: string) => string = String.prototype.trim
? ((input: string) : string => {
return (input || "").trim();
})
: ((input: string) : string => {
return (input || "").replace(/^\s+|\s+$/g,"");
})
如果原生原型不可用,它将回退到正则表达式。
我的使用单个正则表达式来查找需要修剪的情况,并使用该正则表达式的结果来确定所需的子字符串边界:
var illmatch= /^(\s*)(?:.*?)(\s*)$/
function strip(me){
var match= illmatch.exec(me)
if(match && (match[1].length || match[2].length)){
me= me.substring(match[1].length, p.length-match[2].length)
}
return me
}
对此进行的一个设计决策是使用子字符串来执行最终捕获。s/\?:// (进行中间项捕获)并且替换片段变为:
if(match && (match[1].length || match[3].length)){
me= match[2]
}
我在这些 impls 中做了两个性能赌注:
子字符串实现是否复制原始字符串的数据?如果是这样,首先,当需要修剪字符串时,会进行双重遍历,首先是正则表达式(可能是部分),其次是子字符串提取。希望子字符串实现仅引用原始字符串,因此子字符串之类的操作几乎可以免费使用。十指交叉
正则表达式 impl 中的捕获有多好?中期,即产出价值,可能会很长。我还没有准备好相信所有正则表达式 impls 的捕获不会在几百 KB 的输入捕获时犹豫,但我也没有测试(运行时太多,抱歉!)。第二个总是运行捕获;如果您的引擎可以做到这一点而不会受到影响,也许使用上面的一些绳索技术,请务必使用它!
适用于 IE9+ 等浏览器
function trim(text) {
return (text == null) ? '' : ''.trim.call(text);
}