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()函数在浏览器上面支持的问题

 

你可能感兴趣的:(个人解惑,知识学习,前端问题)