trim();方法使用问题

记笔记,方便回忆。自己就是这样写然后总报错。网上查了下如下:

document.getElementById("mobile").value.trim(); //可以

在ie 7 8浏览器中,如果使用trim()属性去除空格的话,则会导致报错。 

$("#account").val().trim();

在网上找了可写成如下:

$.trim($("#account").val());  //Uncaught ReferenceError: $trim is not defined

或者

var a = $("#account").val();

$.trim(a);
jQuery.trim(a);

if(jQuery.trim(a) == '') {
    //函数
}

但是呢$.trim($("#account").val());这个写法并不好用,有时候还是报错。


如要写成这样$("#account").val().trim()在js中写上这个,然后直接在你要去空格的字符串后面跟上 .trim() 即可;

 String.prototype.trim = function () {
return this .replace(/^\s\s*/, '' ).replace(/\s\s*$/, '' );
 }
/*
* 其它
*/


String.prototype.trim = function ()
{
	return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.ltrim = function ()
{
	return this.replace(/(^\s*)/g, "");
}
String.prototype.rtrim = function ()
{
	return this.replace(/(\s*$)/g, "");
}

 

/* 
* Uncaught TypeError: Cannot read property 'trim' of undefined
* https://stackoverflow.com/questions/32733423/uncaught-typeerror-cannot-read-property-trim-of-undefined-in-jquery
*/



You're getting error

Uncaught TypeError: Cannot read property 'trim' of undefined in Jquery

that means, the variable vname is undefined. To prevent this error from occurring, you can use the ternary operator to set the default value of the string to empty string when it is undefined.

var vname = $("#EarningsTypes").val() == undefined ? '' : $("#EarningsTypes").val().trim();
vname = vname.replace(/ /g, '%20');
You can also use || to set the default value

var vname = $("#EarningsTypes").val() || '';
If you're using an older browser that doesn't support trim, you can use polyfill from MDN

if (!String.prototype.trim) {
  String.prototype.trim = function() {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

 

文章

ie 7/8不支持trim的属性的解决方案

jQuery里的trim()函数在浏览器上面支持的问题

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值