您的位置:首页 > Web前端 > JavaScript

在Javascript中对String的一些方法扩展,实现常用的字符串处理。

2008-05-30 12:08 1116 查看
// 类似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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: