JavaScript代码片段字典(二)
获取域名主机
function getHost ( url) {
var host = "null" ;
if ( typeof url == "undefined" || null == url) {
url = window. location. href;
}
var regex = /^\w+\:\/\/([^\/]*).*/ ;
var match = url. match ( regex) ;
if ( typeof match != "undefined" && null != match) {
host = match[ 1 ] ;
}
return host;
}
替换全部
String. prototype. replaceAll = function ( s1, s2) {
return this . replace ( new RegExp ( s1, "gm" ) , s2)
}
转义html标签
function HtmlEncode ( text) {
return text. replace ( /&/g , '&' ) . replace ( /\"/g , '"' ) . replace ( /</g , '<' ) . replace ( />/g , '>' )
}
生JavaScript还原html标签
function HtmlDecode ( text) {
return text. replace ( /&/g , '&' ) . replace ( /"/g , '\"' ) . replace ( /</g , '<' ) . replace ( />/g , '>' )
}
判断是否为数字类型
function isDigit ( value) {
var patrn = /^[0-9]*$/ ;
if ( patrn. exec ( value) == null || value == "" ) {
return false
} else {
return true
}
}
设置cookie值
function setCookie ( name, value, Hours) {
var d = new Date ( ) ;
var offset = 8 ;
var utc = d. getTime ( ) + ( d. getTimezoneOffset ( ) * 60000 ) ;
var nd = utc + ( 3600000 * offset) ;
var exp = new Date ( nd) ;
exp. setTime ( exp. getTime ( ) + Hours * 60 * 60 * 1000 ) ;
document. cookie = name + "=" + escape ( value) + ";path=/;expires=" + exp. toGMTString ( ) + ";domain=360doc.com;"
}
获取cookie值
function getCookie ( name) {
var arr = document. cookie. match ( new RegExp ( "(^| )" + name + "=([^;]*)(;|$)" ) ) ;
if ( arr != null ) return unescape ( arr[ 2 ] ) ;
return null
}
加入收藏夹
function AddFavorite ( sURL, sTitle) {
try {
window. external. addFavorite ( sURL, sTitle)
} catch ( e) {
try {
window. sidebar. addPanel ( sTitle, sURL, "" )
} catch ( e) {
alert ( "加入收藏失败,请使用Ctrl+D进行添加" )
}
}
}
设为首页
function setHomepage ( ) {
if ( document. all) {
document. body. style. behavior = 'url(#default#homepage)' ;
document. body. setHomePage ( 'http://***' )
} else if ( window. sidebar) {
if ( window. netscape) {
try {
netscape. security. PrivilegeManager. enablePrivilege ( "UniversalXPConnect" )
} catch ( e) {
alert ( "该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true" )
}
}
var prefs = Components. classes[ '@mozilla.org/preferences-service;1' ] . getService ( Components. interfaces. nsIPrefBranch) ;
prefs. setCharPref ( 'browser.startup.homepage' , 'http://***' )
}
}
判断IE6
var ua = navigator. userAgent. toLowerCase ( ) ;
var isIE6 = ua. indexOf ( "msie 6" ) > - 1 ;
if ( isIE6) {
try {
document. execCommand ( "BackgroundImageCache" , false , true )
} catch ( e) { }
}