在Javascript中实现对String处理的扩展:Trim(), Left(), IsInt(), IsFloat(), Round() 。
// 类似C#里的Trim
String.prototype.Trim = function(mode)
{
var re;
var str = this;
switch(parseInt(mode))
{
case 1: //去除左边空白
re = /^\s*/g;
break;
case 2: //去除右边空白
re = /\s*$/g;
break;
case 3: //修剪中间多余空白,去除左右空白
str = str.replace(/\s+/g,' ');
re = /(^\s*)|(\s*$)/g;
break;
case 4: //去除所有空白
re = /\s+/g;
break;
default: //去除左右空白
re = /(^\s*)|(\s*$)/g;
break;
}
return str.replace(re,'');
}
// 截取前几个字符,并制定省略符号
String.prototype.Left = function(precision, more)
{
var str = this;
if(!more) more = '';
if(str.length > precision)
return str.substr(0, precision-more.length) + more;
else
return str;
}
// 判断字符串是否为整数
String.prototype.IsInt = function()
{
var Int = parseInt(this,10);
if(isNaN(Int)) return false;
if(Int.toString() != this) return false;
return true;
}
// 判断字符串是否为浮点数
String.prototype.IsFloat = function()
{
var Float = parseFloat(this,10);
if(isNaN(Float)) return false;
if(Float.toString() != this) return false;
return true;
}
// 指定精度并四舍五入
String.prototype.Round = function(precision)
{
var R = Math.pow(10, precision);
return Math.round(this * R) / R;
}
// 指定精度并四舍五入(重载,适应其它类型)
Object.prototype.Round = function(precision)
{
var R = Math.pow(10, precision);
return Math.round(this * R) / R;
}
浙公网安备 33010602011771号