JavaScript参考手册
字符串 | String
string.trim
trim()
方法会从一个字符串的两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LF,CR)。
语法
str.trim()
描述
trim() 方法并不影响原字符串本身,它返回的是一个新的字符串。
描述
该trim()
方法返回从两端删除空白的字符串。trim()
不影响字符串本身的值。
示例
使用 trim()
下面的例子中将显示小写的字符串 'foo':
var orig = ' foo ';
console.log(orig.trim()); // 'foo'
// Another example of .trim() removing whitespace from just one side.
var orig = 'foo ';
console.log(orig.trim()); // 'foo'
备注
如果 trim()
不存在,可以在所有代码前执行下面代码
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
规范
Specification |
Status |
Comment |
---|---|---|
ECMAScript 5.1 (ECMA-262)The definition of 'String.prototype.trim' in that specification. |
Standard |
Initial definition. Implemented in JavaScript 1.8.1. |
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'String.prototype.trim' in that specification. |
Standard |
|
ECMAScript Latest Draft (ECMA-262)The definition of 'String.prototype.trim' in that specification. |
Living Standard |
|
浏览器兼容性
Feature |
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
---|---|---|---|---|---|---|
Basic Support |
(Yes) |
(Yes) |
3.5 |
9 |
10.5 |
5 |
Feature |
Android |
Chrome for Android |
Edge mobile |
Firefox for Android |
IE mobile |
Opera Android |
iOS Safari |
---|---|---|---|---|---|---|---|
Basic Support |
(Yes) |
(Yes) |
(Yes) |
(Yes) |
(Yes) |
(Yes) |
(Yes) |
字符串 | String相关
JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络