1、JavaScript删除字符串前后的空格
String.prototype.trim = function()
{
return this.replace(/(^/s*)|(/s*$)/g, "");
}
2、JavaScript判断是否是数字(功能相当于isNaN)
function isNumber(str)
{
var patt=/^/d+(/./d+)?$/;
return patt.test(str);
}
4、JavaScript判断email地址格式
function isEmail(str)
{
var patt=/^([/w.-])+/@(([/w-])+/.)+([a-zA-Z0-9]{2,4})+$/;
return patt.test(str);
}
5、触发某对象的click事件
function clickIt(elementId)
{
var ele=document.getElementById(elementId);
ele.onclick.call(ele);
}
6、getBrowserType()
function getBrowserType()
{
var patt=/Microsoft/i;
if(patt.test(window.navigator.appName)) return "IE";
patt=/Netscape/i;
if(patt.test(window.navigator.appName)) return "FF";
return "";
}
8、给对象添加事件
function addObjectEvent(objID,eventName,eventFunc)
{
var theObj=document.getElementById(objID);
if(window.attachEvent)//IE
{
theObj.attachEvent(eventName,eventFunc);
}
else if(window.addEventListener)//FireFox
{
eventName = eventName.toString().replace(/on(.*)/i,'$1');
theObj.addEventListener(eventName,eventFunc,true);
}
}
addObjectEvent('the object id','onclick',show);
function show()
{
alert('ok');
}
Note:
IE: attachEvent, detachEvent
FF: addEventListener, removeEventListener
9、给对象移除事件
function removeObjectEvent(objID,eventName,eventFunc)
{
var theObj=document.getElementById(objID);
if(window.detachEvent)//IE
{
theObj.detachEvent(eventName,eventFunc);
}
else if(window.removeEventListener)//FireFox
{
eventName = eventName.toString().replace(/on(.*)/i,'$1');
theObj.removeEventListener(eventName,eventFunc,true);
}
}
removeObjectEvent('the object id','onclick',show);
function show()
{
alert('ok');
}
11、进制转换
/*
* 任意进制转10进制
* 参数num表示待转换的数
* 参数str表示待转换的进制的具体信息,如标准2进制为"01",标准8进制为"01234567"
*/
function toDec(num, str) {
var r = 0;
for(var i = num.length - 1, j = 0; i >= 0; i--, j++) {
var t = str.indexOf(num.charAt(i));
if(t == -1) return "error";
r += t * Math.pow(str.length, j);
}
return r;
}
/*
* 10进制转任意进制
*/
function carrybit(num, str) {
var r = "";
if(str.length > 1) {
if(num >= str.length) {
r += carrybit(Math.floor(num / str.length), str);
r += carrybit(num % str.length, str);
} else {
r = str.substr(num, 1);
}
}
return r;
}
12、money格式化
alert(formatMoney('123456789.126'));
//$123,456,789.13
function formatMoney(strNumber)
{
if(!isNumber(strNumber)) return strNumber;
var nNumber=(Number(strNumber)).toFixed(2);
strNumber=nNumber.toString();
var decimalPart="";
var intPart="";
if(strNumber.indexOf(".")==-1)//no .
{
decimalPart="";
intPart=strNumber;
}
else//yes .
{
decimalPart=strNumber.substring(strNumber.indexOf("."));
intPart=strNumber.substring(0,strNumber.indexOf("."));
}
intPart=intPart.replace(/^(/d*)$/,"$1/,");
var re=/(/d)(/d{3}/,)/;
while(re.test(intPart))
{
intPart=intPart.replace(re,"$1/,$2");
}
intPart=intPart.substring(0,intPart.length-1);
return "$"+intPart+decimalPart;
}
function isNumber(str)
{
var patt=/^/d+(/./d+)?$/;
return patt.test(str);
}