1. Native JavaScript implements string length interception
Copy the code code as follows:
function cutstr(str, len) {
vartemp;
var icount = 0;
var patrn = /[^/x00-/xff]/;
var strre = "";
for (var i = 0; i < str.length; i++) {
if (icount < len - 1) {
temp = str.substr(i, 1);
if (patrn.exec(temp) == null) {
icount = icount + 1
} else {
icount = icount + 2
}
strre += temp
} else {
break
}
}
return strre + "..."
}
2. Native JavaScript to obtain domain name host
Copy the code code as follows:
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;
}
3. Native JavaScript clears spaces
Copy the code code as follows:
String.prototype.trim = function() {
var reExtraSpace = /^/s*(.*?)/s+$/;
return this.replace(reExtraSpace, "$1")
}
4. Replace all with native JavaScript
Copy the code code as follows:
String.prototype.replaceAll = function(s1, s2) {
return this.replace(new RegExp(s1, "gm"), s2)
}
5. Native JavaScript escape html tags
Copy the code code as follows:
function HtmlEncode(text) {
return text.replace(/&/g, '&').replace(//"/g, '"').replace(/</g, '<').replace(/>/g, '>' )
}
6. Native JavaScript restores html tags
Copy the code code as follows:
function HtmlDecode(text) {
return text.replace(/&/g, '&').replace(/"/g, '/"').replace(/</g, '<').replace(/>/g, '>' )
}
7. Native JavaScript time and date format conversion
Copy the code code as follows:
Date.prototype.Format = function(formatStr) {
var str = formatStr;
var Week = ['日', '一', '二', '三', '四', '五', '六'];
str = str.replace(/yyyy|YYYY/, this.getFullYear());
str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100 ));
str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1)) ;
str = str.replace(/M/g, (this.getMonth() + 1));
str = str.replace(/w|W/g, Week[this.getDay()]);
str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
str = str.replace(/d|D/g, this.getDate());
str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
str = str.replace(/h|H/g, this.getHours());
str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
str = str.replace(/m/g, this.getMinutes());
str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
str = str.replace(/s|S/g, this.getSeconds());
return str
}
8. Native JavaScript determines whether it is a numeric type
Copy the code code as follows:
function isDigit(value) {
var patrn = /^[0-9]*$/;
if (patrn.exec(value) == null || value == "") {
return false
} else {
return true
}
}
9. Native JavaScript sets cookie value
Copy the code code as follows:
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;"
}
10. Get cookie value with native JavaScript
Copy the code code as follows:
function getCookie(name) {
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) return unescape(arr[2]);
return null
}
11. Add native JavaScript to favorites
Copy the code code as follows:
function AddFavorite(sURL, sTitle) {
try {
window.external.addFavorite(sURL, sTitle)
} catch(e) {
try {
window.sidebar.addPanel(sTitle, sURL, "")
} catch(e) {
alert("Failed to add to favorites, please use Ctrl+D to add")
}
}
}
12. Set native JavaScript as homepage
Copy the code code as follows:
function setHomepage() {
if (document.all) {
document.body.style.behavior = 'url(#default#homepage)';
document.body.setHomePage('http://www.jq-school.com')
} else if (window.sidebar) {
if (window.netscape) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect")
} catch(e) {
alert("This operation is rejected by the browser. If you want to enable this feature, please enter about:config in the address bar, and then set the value of signed.applets.codebase_principal_support to true")
}
}
var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
prefs.setCharPref('browser.startup.homepage', 'http://www.jq-school.com')
}
}
13. Native JavaScript determines IE6
Copy the code code as follows:
var ua = navigator.userAgent.toLowerCase();
var isIE6 = ua.indexOf("msie 6") > -1;
if (isIE6) {
try {
document.execCommand("BackgroundImageCache", false, true)
} catch(e) {}
}
14. Native JavaScript loads style files
Copy the code code as follows:
function LoadStyle(url) {
try {
document.createStyleSheet(url)
} catch(e) {
var cssLink = document.createElement('link');
cssLink.rel = 'stylesheet';
cssLink.type = 'text/css';
cssLink.href = url;
var head = document.getElementsByTagName('head')[0];
head.appendChild(cssLink)
}
}
15. Native JavaScript returns script content
Copy the code code as follows:
function evalscript(s) {
if(s.indexOf('<script') == -1) return s;
var p = /<script[^/>]*?>([^/x00]*?)<//script>/ig;
var arr = [];
while(arr = p.exec(s)) {
var p1 = /<script[^/>]*?src=/"([^/>]*?)/"[^/>]*?(reload=/"1/")?(?:charset= /"([/w/-]+?)/")?><//script>/i;
var arr1 = [];
arr1 = p1.exec(arr[0]);
if(arr1) {
appendscript(arr1[1], '', arr1[2], arr1[3]);
} else {
p1 = /<script(.*?)>([^/x00]+?)<//script>/i;
arr1 = p1.exec(arr[0]);
appendscript('', arr1[2], arr1[1].indexOf('reload=') != -1);
}
}
return s;
}
16. Native JavaScript clears script content
Copy the code code as follows:
function stripscript(s) {
return s.replace(/<script.*?>.*?<//script>/ig, '');
}
17. Native JavaScript dynamically loads script files
Copy the code code as follows:
function appendscript(src, text, reload, charset) {
var id = hash(src + text);
if(!reload && in_array(id, evalscripts)) return;
if(reload && $(id)) {
$(id).parentNode.removeChild($(id));
}
evalscripts.push(id);
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.id = id;
scriptNode.charset = charset ? charset : (BROWSER.firefox ? document.characterSet : document.charset);
try {
if(src) {
scriptNode.src = src;
scriptNode. = false;
scriptNode.onload = function () {
scriptNode. = true;
JSLOADED[src] = 1;
};
scriptNode.onreadystatechange = function () {
if((scriptNode.readyState == 'loaded' || scriptNode.readyState == 'complete') && !scriptNode. {
scriptNode. = true;
JSLOADED[src] = 1;
}
};
} else if(text){
scriptNode.text = text;
}
document.getElementsByTagName('head')[0].appendChild(scriptNode);
} catch(e) {}
}
18. Native JavaScript returns the element object retrieved by ID
Copy the code code as follows:
function $(id) {
return !id ? null : document.getElementById(id);
}
19. Native JavaScript returns browser version content
Copy the code code as follows:
function browserVersion(types) {
var other = 1;
for(i in types) {
var v = types[i] ? types[i] : i;
if(USERAGENT.indexOf(v) != -1) {
var re = new RegExp(v + '(///|//s)([//d//.]+)', 'ig');
var matches = re.exec(USERAGENT);
var ver = matches != null ? matches[2] : 0;
other = ver !== 0 && v != 'mozilla' ? 0 : other;
}else {
var ver = 0;
}
eval('BROWSER.' + i + '= ver');
}
BROWSER.other = other;
}
20. Common methods for displaying native JavaScript elements
Copy the code code as follows:
function $(id) {
return !id ? null : document.getElementById(id);
}
function display(id) {
var obj = $(id);
if(obj.style.visibility) {
obj.style.visibility = obj.style.visibility == 'visible' ? 'hidden' : 'visible';
} else {
obj.style.display = obj.style.display == '' ? 'none' : '';
}
}
21. There is an insertBefore method in native JavaScript, but unfortunately there is no insertAfter method? Use the following function to implement it
Copy the code code as follows:
function insertAfter(newChild,refChild){
var parElem=refChild.parentNode;
if(parElem.lastChild==refChild){
refChild.appendChild(newChild);
}else{
parElem.insertBefore(newChild,refChild.nextSibling);
}
}
22. Compatible with browser-bound element events in native JavaScript
Copy the code code as follows:
function addEventSamp(obj,evt,fn){
if (obj.addEventListener) {
obj.addEventListener(evt, fn, false);
}else if(obj.attachEvent){
obj.attachEvent('on'+evt,fn);
}
}
23. Native JavaScript is called when the cursor stops behind the text and the text box gains focus.
Copy the code code as follows:
function focusLast(){
var e = event.srcElement;
var r =e.createTextRange();
r.moveStart('character',e.value.length);
r.collapse(true);
r.select();
}
24. Native JavaScript checks whether the URL link is valid
Copy the code code as follows:
function getUrlState(URL){
var xmlhttp = new ActiveXObject("microsoft.xmlhttp");
xmlhttp.Open("GET",URL, false);
try{
xmlhttp.Send();
}catch(e){
}finally{
var result = xmlhttp.responseText;
if(result){
if(xmlhttp.Status==200){
return(true);
}else{
return(false);
}
}else{
return(false);
}
}
}
25. Native JavaScript formatting CSS style code
Copy the code code as follows:
function formatCss(s){//Formatting code
s = s.replace(//s*([/{/}/:/;/,])/s*/g, "$1");
s = s.replace(/;/s*;/g, ";"); //Clear consecutive semicolons
s = s.replace(//,[/s/./#/d]*{/g, "{");
s = s.replace(/([^/s])/{([^/s])/g, "$1 {/n/t$2");
s = s.replace(/([^/s])/}([^/n]*)/g, "$1/n}/n$2");
s = s.replace(/([^/s]);([^/s/}])/g, "$1;/n/t$2");
return s;
}
26. Native JavaScript compresses CSS style code
Copy the code code as follows:
function yasuoCss (s) {//Compression code
s = s.replace(////*(.|/n)*?/*///g, ""); //Delete comment
s = s.replace(//s*([/{/}/:/;/,])/s*/g, "$1");
s = s.replace(//,[/s/./#/d]*/{/g, "{"); //Fault tolerance processing
s = s.replace(/;/s*;/g, ";"); //Clear consecutive semicolons
s = s.match(/^/s*(/S+(/s+/S+)*)/s*$/); //Remove leading and trailing blanks
return (s == null) ? "" : s[1];
}
27. Native JavaScript gets the current path
Copy the code code as follows:
var currentPageUrl = "";
if (typeof this.href === "undefined") {
currentPageUrl = document.location.toString().toLowerCase();
}
else {
currentPageUrl = this.href.toString().toLowerCase();
}
28. Convert native JavaScript IP to integer
Copy the code code as follows:
function _ip2int(ip){
varnum = 0;
ip = ip.split(".");
num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]);
num = num >>> 0;
return num;
}
29. Native JavaScript integer is parsed into IP address
Copy the code code as follows:
function _int2iP(num){
var str;
var tt = new Array();
tt[0] = (num >>> 24) >>> 0;
tt[1] = ((num << 8) >>> 24) >>> 0;
tt[2] = (num << 16) >>> 24;
tt[3] = (num << 24) >>> 24;
str = String(tt[0]) + "." + String(tt[1]) + "." + String(tt[2]) + "." + String(tt[3]);
return str;
}
30. Native JavaScript implements checkbox selection or none selection
Copy the code code as follows:
function checkAll() {
var selectall = document.getElementById("selectall");
var allbox = document.getElementsByName("allbox");
if (selectall.checked) {
for (var i = 0; i < allbox.length; i++) {
allbox[i].checked = true;
}
} else {
for (var i = 0; i < allbox.length; i++) {
allbox[i].checked = false;
}
}
}
Note: Mobile (31~40)
31. Native JavaScript determines whether the device is mobile
Copy the code code as follows:
function isMobile(){
if (typeof this._isMobile === 'boolean'){
return this._isMobile;
}
var screenWidth = this.getScreenWidth();
var fixViewPortsExperiment = rendererModel.runningExperiments.FixViewport || rendererModel.runningExperiments.fixviewport;
var fixViewPortsExperimentRunning = fixViewPortsExperiment && (fixViewPortsExperiment.toLowerCase() === "new");
if(!fixViewPortsExperiment){
if(!this.isAppleMobileDevice()){
screenWidth = screenWidth/window.devicePixelRatio;
}
}
var isMobileScreenSize = screenWidth < 600;
var isMobileUserAgent = false;
this._isMobile = isMobileScreenSize && this.isTouchScreen();
return this._isMobile;
}
32. Native JavaScript determines whether mobile device access
Copy the code code as follows:
function isMobileUserAgent(){
return (/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.userAgent.toLowerCase()));
}
33. Native JavaScript determines whether Apple mobile device access
Copy the code code as follows:
function isAppleMobileDevice(){
return (/iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase()));
}
34. Native JavaScript determines whether Android mobile device access
Copy the code code as follows:
function isAndroidMobileDevice(){
return (/android/i.test(navigator.userAgent.toLowerCase()));
}
35. Native JavaScript determines whether the screen is touched
Copy the code code as follows:
function isTouchScreen(){
return (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
}
36. Native JavaScript determines whether it is in Google Chrome on Android
Copy the code code as follows:
function isNewChromeOnAndroid(){
if(this.isAndroidMobileDevice()){
var userAgent = navigator.userAgent.toLowerCase();
if((/chrome/i.test(userAgent))){
var parts = userAgent.split('chrome/');
var fullVersionString = parts[1].split(" ")[0];
var versionString = fullVersionString.split('.')[0];
var version = parseInt(versionString);
if(version >= 27){
return true;
}
}
}
return false;
}
37. Native JavaScript determines whether to open the window
Copy the code code as follows:
function isViewportOpen() {
return !!document.getElementById('wixMobileViewport');
}
38. Native JavaScript to obtain the initial size of mobile devices
Copy the code code as follows:
function getInitZoom(){
if(!this._initZoom){
var screenWidth = Math.min(screen.height, screen.width);
if(this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()){
screenWidth = screenWidth/window.devicePixelRatio;
}
this._initZoom = screenWidth /document.body.offsetWidth;
}
return this._initZoom;
}
39. Native JavaScript to maximize the size of mobile devices
Copy the code code as follows:
function getZoom(){
var screenWidth = (Math.abs(window.orientation) === 90) ? Math.max(screen.height, screen.width) : Math.min(screen.height, screen.width);
if(this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()){
screenWidth = screenWidth/window.devicePixelRatio;
}
var FixViewPortsExperiment = rendererModel.runningExperiments.FixViewport || rendererModel.runningExperiments.fixviewport;
var FixViewPortsExperimentRunning = FixViewPortsExperiment && (FixViewPortsExperiment === "New" || FixViewPortsExperiment === "new");
if(FixViewPortsExperimentRunning){
return screenWidth / window.innerWidth;
}else{
return screenWidth / document.body.offsetWidth;
}
}
40. Native JavaScript to get the mobile device screen width
Copy the code code as follows:
function getScreenWidth(){
var smallerSide = Math.min(screen.width, screen.height);
var fixViewPortsExperiment = rendererModel.runningExperiments.FixViewport || rendererModel.runningExperiments.fixviewport;
var fixViewPortsExperimentRunning = fixViewPortsExperiment && (fixViewPortsExperiment.toLowerCase() === "new");
if(fixViewPortsExperiment){
if(this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()){
smallerSide = smallerSide/window.devicePixelRatio;
}
}
return smallerSide;
}
41. Native JavaScript perfectly determines whether it is a URL
Copy the code code as follows:
function IsURL(strUrl) {
var regular = /^/b(((https?|ftp):////)?[-a-z0-9]+(/.[-a-z0-9]+)*/.(?:com|edu |gov|int|mil|net|org|biz|info|name|museum|a sia|coop|aero|[az][az]|((25[0-5])|(2[0-4]/d)|(1/d/d)|([1-9]/d )|/d))/b(//[-a-z0-9_:/@&?=+,.!//~%/$]*)?)$/i
if (regular.test(strUrl)) {
return true;
}
else {
return false;
}
}
42. Native JavaScript retrieves element objects based on style names
Copy the code code as follows:
function getElementsByClassName(name) {
var tags = document.getElementsByTagName('*') || document.all;
var els = [];
for (var i = 0; i < tags.length; i++) {
if (tags[i].className) {
var cs = tags[i].className.split(' ');
for (var j = 0; j < cs.length; j++) {
if (name == cs[j]) {
els.push(tags[i]);
break
}
}
}
}
return els
}
43. Native JavaScript determines whether it starts with a certain string
Copy the code code as follows:
String.prototype.startWith = function (s) {
return this.indexOf(s) == 0
}
44. Native JavaScript determines whether it ends with a certain string
Copy the code code as follows:
String.prototype.endWith = function (s) {
var d = this.length - s.length;
return (d >= 0 && this.lastIndexOf(s) == d)
}
45. Native JavaScript returns the version number of IE browser
Copy the code code as follows:
function getIE(){
if (window.ActiveXObject){
var v = navigator.userAgent.match(/MSIE ([^;]+)/)[1];
return parseFloat(v.substring(0, v.indexOf(".")))
}
return false
}
46. Get page height with native JavaScript
Copy the code code as follows:
function getPageHeight(){
var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat"
?a
: g.documentElement;
return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight);
}
47. Native JavaScript gets page scrollLeft
Copy the code code as follows:
function getPageScrollLeft(){
var a = document;
return a.documentElement.scrollLeft || a.body.scrollLeft;
}
48. Native JavaScript obtains the visible width of the page
Copy the code code as follows:
function getPageViewWidth(){
var d = document, a = d.compatMode == "BackCompat"
?d.body
: d.documentElement;
return a.clientWidth;
}
49. Native JavaScript to get page width
Copy the code code as follows:
function getPageWidth(){
var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat"
?a
: g.documentElement;
return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth);
}
50. Native JavaScript gets page scrollTop
Copy the code code as follows:
function getPageScrollTop(){
var a = document;
return a.documentElement.scrollTop || a.body.scrollTop;
}
61. Native JavaScript solves offsetX compatibility issues
Copy the code code as follows:
// OffsetX/Y is not supported for Firefox
function getOffset(e){
var target = e.target, //The currently triggered target object
eventCoord,
pageCoord,
offsetCoord;
// Calculate the distance from the current trigger element to the document
pageCoord = getPageCoord(target);
// Calculate the distance from the cursor to the document
eventCoord = {
X : window.pageXOffset + e.clientX,
Y : window.pageYOffset + e.clientY
};
// Subtract to obtain the coordinates of the cursor to the first positioned parent element
offsetCoord = {
X : eventCoord.X - pageCoord.X,
Y : eventCoord.Y - pageCoord.Y
};
return offsetCoord;
}
function getPageCoord(element){
var coord = { X : 0, Y : 0 };
// Calculate from the current trigger element to the root node,
//The sum of offsetLeft or offsetTop values of offsetParent elements at all levels
while (element){
coord.X += element.offsetLeft;
coord.Y += element.offsetTop;
element = element.offsetParent;
}
return coord;
}
62. Regular expressions commonly used in native JavaScript
Copy the code code as follows:
//Positive integer
/^[0-9]*[1-9][0-9]*$/;
//Negative integer
/^-[0-9]*[1-9][0-9]*$/;
//Positive floating point number
/^(([0-9]+/.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*/ .[0-9]+)|([0-9]*[1-9][0-9]*))$/;
//Negative floating point number
/^(-(([0-9]+/.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9] */.[0-9]+)|([0-9]*[1-9][0-9]*)))$/;
//Floating point number
/^(-?/d+)(/./d+)?$/;
//email address
/^[/w-]+(/.[/w-]+)*@[/w-]+(/.[/w-]+)+$/;
//url address
/^[a-zA-z]+://(/w+(-/w+)*)(/.(/w+(-/w+)*))*(/?/S*)?$/;
//Year/month/day (year-month-day, year.month.day)
/^(19|20)/d/d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9] |3[01])$/;
//Match Chinese characters
/[/u4e00-/u9fa5]/;
//Whether the matching account is legal (starting with a letter, 5-10 bytes allowed, alphanumeric underscores allowed)
/^[a-zA-Z][a-zA-Z0-9_]{4,9}$/;
//Regular expression to match blank lines
//n/s*/r/;
//Match Chinese postal code
/[1-9]/d{5}(?!/d)/;
//Match ID card
//d{15}|/d{18}/;
//Match domestic phone numbers
/(/d{3}-|/d{4}-)?(/d{8}|/d{7})?/;
//Match IP address
/((2[0-4]/d|25[0-5]|[01]?/d/d?)/.){3}(2[0-4]/d|25[0-5 ]|[01]?/d/d?)/;
//Regular expression matching leading and trailing whitespace characters
/^/s*|/s*$/;
//Regular expression matching HTML tags
< (/S*?)[^>]*>.*?|< .*? />;
63. Native JavaScript implements a common method of returning to the top
Copy the code code as follows:
function backTop(btnId) {
var btn = document.getElementById(btnId);
var d = document.documentElement;
var b = document.body;
window.onscroll = set;
btn.style.display = "none";
btn.onclick = function() {
btn.style.display = "none";
window.onscroll = null;
this.timer = setInterval(function() {
d.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1);
b.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1);
if ((d.scrollTop + b.scrollTop) == 0) clearInterval(btn.timer, window.onscroll = set);
},
10);
};
function set() {
btn.style.display = (d.scrollTop + b.scrollTop > 100) ? 'block': "none"
}
};
backTop('goTop');
64. Native JavaScript obtains the GET parameter value in the URL
Copy the code code as follows:
// Usage: If the address is test.htm?t1=1&t2=2&t3=3, then you can get: GET["t1"], GET["t2"], GET["t3"]
function get_get(){
querystr = window.location.href.split("?")
if(querystr[1]){
GETs = querystr[1].split("&")
GET =newArray()
for(i=0;i<GETs.length;i++){
tmp_arr = GETs[i].split("=")
key=tmp_arr[0]
GET[key] = tmp_arr[1]
}
}
return querystr[1];
}
65. Native JavaScript implements the universal method of selecting all
Copy the code code as follows:
function checkall(form, prefix, checkall) {
var checkall = checkall ? checkall : 'chkall';
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.type=="checkbox"){
e.checked = form.elements[checkall].checked;
}
}
}
66. Native JavaScript implements the universal method of deselecting all
Copy the code code as follows:
function uncheckAll(form) {
for (var i=0;i<form.elements.length;i++){
var e = form.elements[i];
if (e.name != 'chkall')
e.checked=!e.checked;
}
}
67. Native JavaScript implements a common method for opening a form
Copy the code code as follows:
function openWindow(url,windowName,width,height){
var x = parseInt(screen.width / 2.0) - (width / 2.0);
var y = parseInt(screen.height / 2.0) - (height / 2.0);
var isMSIE= (navigator.appName == "Microsoft Internet Explorer");
if (isMSIE) {
var p = "resizable=1,location=no,scrollbars=no,width=";
p = p+width;
p = p+",height=";
p = p+height;
p = p+",left=";
p = p+x;
p = p+",top=";
p = p+y;
retval = window.open(url, windowName, p);
} else {
var win = window.open(url, "ZyiisPopup", "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",dialog=yes,modal=yes,width=" + width + ",height=" + height + ",resizable=no" );
eval("try { win.resizeTo(width, height); } catch(e) { }");
win.focus();
}
}
68. Native JavaScript determines whether it is a client device
Copy the code code as follows:
function client(o){
var b = navigator.userAgent.toLowerCase();
var t = false;
if (o == 'isOP'){
t = b.indexOf('opera') > -1;
}
if (o == 'isIE'){
t = b.indexOf('msie') > -1;
}
if (o == 'isFF'){
t = b.indexOf('firefox') > -1;
}
return t;
}
69. Native JavaScript to get the value of the radio button
Copy the code code as follows:
function get_radio_value(field){
if(field&&field.length){
for(var i=0;i<field.length;i++){
if(field[i].checked){
return field[i].value;
}
}
}else {
return ;
}
}
70. Native JavaScript to get the value of the checkbox
Copy the code code as follows:
function get_checkbox_value(field){
if(field&&field.length){
for(var i=0;i<field.length;i++){
if(field[i].checked && !field[i].disabled){
return field[i].value;
}
}
}else {
return;
}
}
(71~80) Verification This article is mainly about 10 commonly used form verification functions, including email, dangerous characters, verification length, verification URL, verification of decimals, integers, floating point numbers and other commonly used verifications. With these codes Fragment, normal form validation does not require jquery validation plug-in, I hope it can help everyone. . .
71. Native JavaScript determines whether it is an email address
Copy the code code as follows:
function isEmail(str){
var re=/^/w+((-/w+)|(/./w+))*/@[A-Za-z0-9]+((/.|-)[A-Za-z0-9] +)*/.[A-Za-z0-9]+$/;
if (re.test(str) != true) {
return false;
}else{
return true;
}
}
72. Native JavaScript determines whether there are dangerous characters in the list
Copy the code code as follows:
function isValidReg(chars){
var re=/<|>|/[|/]|/{|/}|『|』|※|○|●|◎|§|△|▲|☆|★|◇|◆|□|||| |⊙||ㄅ|ㄆ|ㄇ|ㄈ|ㄉ|ㄊ|ㄋ|ㄌ| ㄍ|ㄎ|ㄏ|ㄐ|ㄑ|ㄒ|ㄓ|ㄔ|ㄕ|ㄖ|ㄗ|ㄘ|ㄙ|ㄚ|ㄛ|ㄜ|ㄝ|ㄞ| ㄟ|ㄢ|ㄣ|ㄤ|ㄥ|ㄦ|ㄧ|ㄨ|ㄩ|■|||/*|@|#|/^|///;
if (re.test(chars) == true) {
return false;
}else{
return true;
}
}
73. Native JavaScript determines whether a string is greater than the specified length
Copy the code code as follows:
function isValidLength(chars, len) {
if (chars. length < len) {
return false;
}
return true;
}
74. Native JavaScript determines whether a string is a URL and is not case-sensitive.
Copy the code code as follows:
function isValidURL( chars ) {
var re=/^([hH][tT]{2}[pP]:////|[hH][tT]{2}[pP][sS]:////)(/S+/. /S+)$/;
if (!isNULL(chars)) {
chars = jsTrim(chars);
if (chars.match(re) == null)
return false;
else
return true;
}
return false;
}
75. Native JavaScript determines whether a string is a decimal
Copy the code code as follows:
function isValidDecimal( chars ) {
var re=/^/d*/.?/d{1,2}$/;
if (chars.match(re) == null)
return false;
else
return true;
}
76. Native JavaScript determines whether a string is an integer
Copy the code code as follows:
function isNumber(chars) {
var re=/^/d*$/;
if (chars.match(re) == null)
return false;
else
return true;
}
77. Native JavaScript determines whether a string is a floating point number
Copy the code code as follows:
function isFloat( str ) {
for(i=0;i<str.length;i++) {
if ((str.charAt(i)<"0" || str.charAt(i)>"9")&& str.charAt(i) != '.'){
return false;
}
}
return true;
}
78. Native JavaScript determines whether the characters are A-Za-z English letters
Copy the code code as follows:
function isLetters(str){
var re=/^[A-Za-z]+$/;
if (str.match(re) == null)
return false;
else
return true;
}
79. Native JavaScript determines whether a string is a zip code
Copy the code code as follows:
function isValidPost( chars ) {
var re=/^/d{6}$/;
if (chars.match(re) == null)
return false;
else
return true;
}
80. Native JavaScript determines whether the character is NULL
Copy the code code as follows:
function isNULL(chars) {
if (chars == null)
return true;
if (jsTrim(chars).length==0)
return true;
return false;
}
81. Native JavaScript uses regular expressions to extract all URLs in the page code
Copy the code code as follows:
var aa = document.documentElement.outerHTML.match(/(url/(|src=|href=)[/"/']*([^/"/'/(/)/</>/[/] ] +)[/"/'/)]*|(http:////[/w/-/.]+[^/"/'/(/)/</>/[/] ]+)/ig).join("/r/n").replace(/^(src=|href=|url/()[/"/']*|[/"/'/>/) ] *$/igm,"");
alert(aa);
82. Native JavaScript uses regular expressions to clear identical arrays (low efficiency)
Copy the code code as follows:
Array.prototype.unique=function(){
return this.reverse().join(",").match(/([^,]+)(?!.*/1)/ig).reverse();
}
83. Native JavaScript uses regular expressions to clear identical arrays (high efficiency)
Copy the code code as follows:
String.prototype.unique=function(){
var x=this.split(/[/r/n]+/);
var y='';
for(var i=0;i<x.length;i++){
if(!new RegExp("^"+x[i].replace(/([^/w])/ig,"//$1")+"$","igm").test(y)){
y+=x[i]+"/r/n"
}
}
return y
}
84. Native JavaScript uses regular expressions to sort alphabetically and sort each row in an array
Copy the code code as follows:
function SetSort(){
var text=K1.value.split(/[/r/n]/).sort().join("/r/n");//order
var test=K1.value.split(/[/r/n]/).sort().reverse().join("/r/n");//reverse order
K1.value=K1.value!=text?text:test;
}
85. Native JavaScript string reverse order
Copy the code code as follows:
function IsReverse(text){
return text.split('').reverse().join('');
}
86. Native JavaScript uses regular expressions to clear scripts in html code
Copy the code code as follows:
function clear_script(){
K1.value=K1.value.replace(/<script.*?>[/s/S]*?<//script>|/s+on[a-zA-Z]{3,16}/s ?=/s?"[/s/S]*?"|/s+on[a-zA-Z]{3,16}/s?=/s?'[/s/S]*?'| /s+on[a-zA-Z]{3,16}/s?=[^ >]+/ig,"");
}
87. Native JavaScript dynamically executes JavaScript scripts
Copy the code code as follows:
function javascript(){
try{
eval(K1.value);
}catch(e){
alert(e.message);
}
}
88. Native JavaScript dynamically executes VBScript scripts
Copy the code code as follows:
function vbscript(){
try{
var script=document.getElementById("K1").value;
if(script.trim()=="")return;
window.execScript('On Error Resume Next /n'+script+'/n If Err.Number<>0 Then /n MsgBox "Please enter the correct VBScript script!",48,"Script error!" /n End If' ,"vbscript")
}catch(e){
alert(e.message);
}
}
89. Native JavaScript implements the amount capitalization conversion function
Copy the code code as follows:
function transform(tranvalue) {
try {
var i = 1;
var dw2 = new Array("", "10,000", "100 million"); //Large unit
var dw1 = new Array("十", "百", "千"); //Small unit
var dw = new Array("zero", "one", "two", "three", "four", "five", "lu", "seven", "eight", "nine"); //Integer Partially used
//The following is converted from lowercase to uppercase and displayed in the total uppercase text box
//Separate integers and decimals
var source = splits(tranvalue);
var num = source[0];
var dig = source[1];
//Convert the integer part
var k1 = 0; //Small units
var k2 = 0; //Large unit of calculation
var sum = 0;
var str = "";
var len = source[0].length; //The length of the integer
for (i = 1; i <= len; i++) {
var n = source[0].charAt(len - i); //Get a number in a certain digit
varbn = 0;
if (len - i - 1 >= 0) {
bn = source[0].charAt(len - i - 1); //Get the number before a certain digit
}
sum = sum + Number(n);
if (sum != 0) {
str = dw[Number(n)].concat(str); //Get the uppercase number corresponding to the number and insert it in front of the str string
if (n == '0') sum = 0;
}
if (len - i - 1 >= 0) { //Within the range of numbers
if (k1 != 3) { //Add small unit
if (bn != 0) {
str = dw1[k1].concat(str);
}
k1++;
} else { //Do not add small units, increase units
k1 = 0;
var temp = str.charAt(0);
if (temp == "10,000" || temp == "100 million") //If there is no number before the large unit, the large unit will be discarded.
str = str.substr(1, str.length - 1);
str = dw2[k2].concat(str);
sum = 0;
}
}
if (k1 == 3) //If the small unit reaches a thousand, the large unit will be increased by one.
{
k2++;
}
}
//Convert decimal part
var strdig = "";
if (dig != "") {
var n = dig.charAt(0);
if (n != 0) {
strdig += dw[Number(n)] + "angle"; //Add numbers
}
var n = dig.charAt(1);
if (n != 0) {
strdig += dw[Number(n)] + "minutes"; //Add numbers
}
}
str += "元" + strdig;
} catch(e) {
return "0 yuan";
}
return str;
}
//Split integers and decimals
function splits(tranvalue) {
var value = new Array('', '');
temp = tranvalue.split(".");
for (var i = 0; i < temp.length; i++) {
value[i] = temp[i];
}
return value;
}
90. A large collection of regular expressions commonly used in native JavaScript
Copy the code code as follows:
Regular expression to match Chinese characters: [/u4e00-/u9fa5]
Match double-byte characters (including Chinese characters): [^/x00-/xff]
Regular expression to match empty lines: /n[/s| ]*/r
Regular expression matching HTML tags: <(.*)>.*<///1>|<(.*) //>
Regular expression matching leading and trailing spaces: (^/s*)|(/s*$)
Regular expression matching IP addresses: /(/d+)/.(/d+)/.(/d+)/.(/d+)/g
Regular expression matching email addresses: /w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*
Regular expression to match URL: http://(/[/w-]+/.)+[/w-]+(/[/w- ./?%&=]*)?
sql statement: ^(select|drop|delete|create|update|insert).*$
Non-negative integer: ^/d+$
Positive integer: ^[0-9]*[1-9][0-9]*$
Non-positive integers: ^((-/d+)|(0+))$
Negative integers: ^-[0-9]*[1-9][0-9]*$
Integer: ^-?/d+$
Non-negative floating point number: ^/d+(/./d+)?$
Positive floating point number: ^((0-9)+/.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9] */.[0-9]+)|([0-9]*[1-9][0-9]*))$
Non-positive floating point number: ^((-/d+/./d+)?)|(0+(/.0+)?))$
English string: ^[A-Za-z]+$
English uppercase string: ^[AZ]+$
English lowercase string: ^[az]+$
English character and numeric string: ^[A-Za-z0-9]+$
Alphanumeric plus underline string: ^/w+$
E-mail address: ^[/w-]+(/.[/w-]+)*@[/w-]+(/.[/w-]+)+$
URL: ^[a-zA-Z]+://(/w+(-/w+)*)(/.(/w+(-/w+)*))*(/?/s*)?$ Or: ^http:////[A-Za-z0-9]+/.[A-Za-z0-9]+[//=/?%/-&_~`@[/]/': +!]*([^<>/"/"])*$
Postal code: ^[1-9]/d{5}$
Phone number: ^((/(/d{2,3}/))|(/d{3}/-))?(/(0/d{2,3}/)|0/d{2, 3}-)?[1-9]/d{6,7}(/-/d{1,4})?$
Mobile phone number: ^((/(/d{2,3}/))|(/d{3}/-))?13/d{9}$
Double-byte characters (including Chinese characters): ^/x00-/xff
Match leading and trailing spaces: (^/s*)|(/s*$)
Match HTML tags: <(.*)>.*<///1>|<(.*) //>
Match empty lines: /n[/s| ]*/r
Extract network links in the information: (h|H)(r|R)(e|E)(f|F) *= *('|")?(/w|//|//|/.)+ ('|"| *|>)?
Extract the email address in the message: /w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*
Extract the image link in the message: (s|S)(r|R)(c|C) *= *('|")?(/w|//|//|/.)+('|"| *|>)?
Extract the IP address in the message: (/d+)/.(/d+)/.(/d+)/.(/d+)
Extract the Chinese mobile phone number in the message: (86)*0*13/d{9}
Extract the Chinese landline phone number in the message: (/(/d{3,4}/)|/d{3,4}-|/s)?/d{8}
Extract Chinese phone numbers (including mobile and landline phones) from the message: (/(/d{3,4}/)|/d{3,4}-|/s)?/d{7,14}
Extract the Chinese postal code in the information: [1-9]{1}(/d+){5}
Extract floating point numbers (i.e. decimals) in the information: (-?/d*)/.?/d+
Extract any number from the message: (-?/d*)(/./d+)?
IP: (/d+)/.(/d+)/.(/d+)/.(/d+)
Telephone area code: ^0/d{2,3}$
Tencent QQ number: ^[1-9]*[1-9][0-9]*$
Account number (starts with a letter, allows 5-16 bytes, allows alphanumeric underscores): ^[a-zA-Z][a-zA-Z0-9_]{4,15}$
Chinese, English, numbers and underline: ^[/u4e00-/u9fa5_a-zA-Z0-9]+$
91. Native JavaScript implements the resize operation of the form change event (compatible with all browsers)
Copy the code code as follows:
(function(){
var fn = function(){
var w = document.documentElement ? document.documentElement.clientWidth : document.body.clientWidth
,r = 1255
,b = Element.extend(document.body)
,classname = b.className;
if(w < r){
//Perform the corresponding operation when the width of the form is less than 1255
}else{
//Perform the corresponding operation when the width of the form is greater than 1255
}
}
if(window.addEventListener){
window.addEventListener('resize', function(){ fn(); });
}else if(window.attachEvent){
window.attachEvent('onresize', function(){ fn(); });
}
fn();
})();
92. Native JavaScript uses regular rules to clear spaces and divide left and right
Copy the code code as follows:
function ltrim(s){ return s.replace( /^(/s*| *)/, ""); }
function rtrim(s){ return s.replace( /(/s*| *)$/, ""); }
function trim(s){ return ltrim(rtrim(s));}
93. Native JavaScript determines whether a variable is null
Copy the code code as follows:
/**
* Determine whether the variable is empty
* undefined, null, '', false, 0, [], {} all return true, otherwise return false
*/
function empty(v){
switch (typeof v){
case 'undefined' : return true;
case 'string' : if(trim(v).length == 0) return true; break;
case 'boolean' : if(!v) return true; break;
case 'number' : if(0 === v) return true; break;
case 'object' :
if(null === v) return true;
if(undefined !== v.length && v.length==0) return true;
for(var k in v){return false;} return true;
break;
}
return false;
}
94. Native JavaScript implements base64 decoding
Copy the code code as follows:
function base64_decode(data){
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,ac = 0,dec = "",tmp_arr = [];
if (!data) { return data; }
data += '';
do {
h1 = b64.indexOf(data.charAt(i++));
h2 = b64.indexOf(data.charAt(i++));
h3 = b64.indexOf(data.charAt(i++));
h4 = b64.indexOf(data.charAt(i++));
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >> 16 & 0xff;
o2 = bits >> 8 & 0xff;
o3 = bits & 0xff;
if (h3 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1);
} else if (h4 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1, o2);
} else {
tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
}
} while (i < data.length);
dec = tmp_arr.join('');
dec = utf8_decode(dec);
return dec;
}
95. Native JavaScript implements utf8 decoding
Copy the code code as follows:
function utf8_decode(str_data){
var tmp_arr = [],i = 0,ac = 0,c1 = 0,c2 = 0,c3 = 0;str_data += '';
while (i < str_data.length) {
c1 = str_data.charCodeAt(i);
if (c1 < 128) {
tmp_arr[ac++] = String.fromCharCode(c1);
i++;
} else if (c1 > 191 && c1 < 224) {
c2 = str_data.charCodeAt(i + 1);
tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = str_data.charCodeAt(i + 1);
c3 = str_data.charCodeAt(i + 2);
tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return tmp_arr.join('');
}
96. Native JavaScript obtains the width and height of the visible range of the form
Copy the code code as follows:
function getViewSize(){
var de=document.documentElement;
var db=document.body;
var viewing = de.clientWidth == 0? Db.clientWidth: de.clientWidth;
var viewh = de.clientheight == 0? Db.clientheight: de.clientheight;
Return array (viewww, viewh);
}
97. Native JavaScript judge the IE version number (both simple and backward!)
Copy the code code as follows:
var _Ie = (FUNCTION () {
var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
Return v> 4? V: false;
} ());
98. Native JavaScript Get the browser version number
Copy the code code as follows:
Function BrowserVersion (Types) {
var Other = 1;
for (I in Types) {
var v = types [i]? Types [i]: i;
if (useragent.indexof (v)! = -1) {
var re = new regexp (v + '(//////s|/s|:) (=/d//. ,+)', 'ieg');
var matalches = Re.exec (userAgent);
var Ver = Matches! = NULL? Matches [2]: 0;
Other = Ver! == 0 && V! = 'Mozilla'? 0: Other;
} else {
var Ver = 0;
}
EVAL ('Browser.' + I + '= Ver');
}
Browser.oTher = Other;
}
99. Native JavaScript half -angle converted into a full -angle function
Copy the code code as follows:
Function Todbc (STR) {
var result = '';
for (var I = 0; I <str.Length; i ++) {
code = str.charcodeat (i);
if (code> = 33 && code <= 126) {
Result + = string.fromcharcode (str.charcodet (i) + 65248);
} else if (code == 32) {
Result + = string.fromcharcode (str.charcodeat (i) + 12288-32);
}else{
result += str.charat (i);
}
}
return result;
}
100. Native JavaScript full -angle converted into a half -angle function
Copy the code code as follows:
Function TOCDB (STR) {
var result = '';
for (var I = 0; I <str.Length; i ++) {
code = str.charcodeat (i);
if (code> = 65281 && code <= 65374) {
Result += string.fromcharcode (str.charcodeat (i) -65248);
} else if (code == 12288) {
Result + = string.fromcharcode (str.charcodeat (i) -1288 + 32);
}else{
result += str.charat (i);
}
}
return result;
}