Summary of common actions in javascript
- 2020-03-30 03:49:37
- OfStack
This article has compiled and summarized a variety of common javascript operations, including strings, times, forms, regular validation, and so on. Has the extremely high reference value. Share with you for your reference. Specific methods are as follows:
//#region date operation
//String converts to time.
function stringtoTime(date1) {
var dt = new Date(Date.parse(date1.replace(/-/g, "/")));
return dt;
}
//Var date1 = "2013-06-08 15:23:31" or "2013/6/8 9:9:00" format;
//-------------------------------------------------------------
//Date formatting
Date.prototype.format = function (format) {
var o = {
"M+": this.getMonth() + 1, //month
"d+": this.getDate(), //day
"h+": this.getHours(), //hour
"m+": this.getMinutes(), //minute
"s+": this.getSeconds(), //second
"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
"S": this.getMilliseconds() //millisecond
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
}
////Method of use
//alert(newdate.format("yyyy-MM-dd"));
//alert(newdate.format("MM/dd/yyyy"));
//var nowStr = now.format("yyyy-MM-dd hh:mm:ss"); Math.round(Math.random() * 10000)
////Usage 2:
//var testDate = new Date();
//Var testStr = testdate. format("yyyy year MM month dd hh hour MM minute ss second ");
////Example:
//Alert (testdate. format("yyyy year MM month dd day "));
//-------------------------------------------------------------
//Set the date in the period (array)
function SetFlag(start, end) {
var cdate = Array();
cdate = start.split("-");
var cd = cdate[1] + "/" + cdate[2] + "/" + cdate[0];
var dayNum = DateDiff(end, start);
for (var i = 0; i <= dayNum; i++) {
flag.push(AddDays(cd, i));
}
} //end fun
//The new date after the date plus the number of days.
function AddDays(date, days) {
var nd = new Date(date);
nd = nd.valueOf();
nd = nd + days * 24 * 60 * 60 * 1000;
nd = new Date(nd);
//Alert (nd) getFullYear () + "years" + (nd) getMonth () + 1) + "month" + nd. GetDate () + ", ");
var y = nd.getFullYear();
var m = nd.getMonth() + 1;
var d = nd.getDate();
if (m <= 9) m = "0" + m;
if (d <= 9) d = "0" + d;
var cdate = y + "-" + m + "-" + d;
return cdate;
}
//The difference between the two dates (d1 - d2).
function DateDiff(d1, d2) {
var day = 24 * 60 * 60 * 1000;
try {
var dateArr = d1.split("-");
var checkDate = new Date();
checkDate.setFullYear(dateArr[0], dateArr[1] - 1, dateArr[2]);
var checkTime = checkDate.getTime();
var dateArr2 = d2.split("-");
var checkDate2 = new Date();
checkDate2.setFullYear(dateArr2[0], dateArr2[1] - 1, dateArr2[2]);
var checkTime2 = checkDate2.getTime();
var cha = (checkTime - checkTime2) / day;
return cha;
} catch (e) {
return false;
}
} //end fun
//#endregion
//# region URL
function getQueryStringByName(name) {
var result = location.search.match(new RegExp("[?&]" + name + "=([^&]+)", "i"));
if (result == null || result.length < 1)
return "";
return result[1];
}
function GetQueryString(name) {
//If the link has no parameters, or the link does not have the parameters we want to get, return null
if (location.href.indexOf("?") == -1 || location.href.indexOf(name + '=') == -1) {
return '';
}
//Gets the parameters section of the link
var queryString = location.href.substring(location.href.indexOf("?") + 1);
//Separate parameter pairs ? Key = value&key 2 = value2
var parameters = queryString.split("&");
var pos, paraName, paraValue;
for (var i = 0; i < parameters.length; i++) {
//Get the equal sign
pos = parameters[i].indexOf('=');
if (pos == -1) {
continue;
}
//Get name and value
paraName = parameters[i].substring(0, pos);
paraValue = parameters[i].substring(pos + 1);
//If the name of the query is equal to the current name, the current value is returned, and the + sign in the link is restored to a space
if (paraName == name) {
return unescape(paraValue.replace(/+/g, " "));
}
}
return '';
}
function getCurrentUrlName() {
var url = window.location.href;
url = url.toLocaleLowerCase();
if (url == undefined || url == "")
return "";
var item = url.toString().split("/");
var name = item[item.length - 1];
name = name.toString().split(".");
if (name.length == 2)
return name[0].toString();
else return "";
}
//#endregion
//#region string operation
function getCustomLengtStr(strString, strStart, intLen) {
if (strString != undefined && strString != "" && strString != null) {
var CLen = strString.toString().length;
if ((strStart + intLen) <= CLen - 1) {
if (strStart < 0) strStart = 0;
return strString.toString().substr(strStart, Number(intLen));
} else {
//Length out of bounds, returns the original data
return strString;
}
} else return "";
}
function getCustomLengtStr(strString, intStart, intEnd) {
if (strString != undefined && strString != "" && strString != null) {
var Clen = strString.toString().length - 1;
if (Number(intEnd) <= Clen) {
if (intStart < 0) intStart = 0;
else if (intStart > Clen) intStart = Clen;
return strString.toString().substring(intStart, intEnd);
} else {
//Length out of bounds, returns the original data
return strString;
}
} else return "";
}
//#endregion
//Set #region as home page, add favorites
//Set to the home page
function SetHome() {
if (document.all) {
document.body.style.behavior = "url(#default#homepage)";
var url = window.location.href;
document.body.setHomePage(url);
} else {
alert("Set to the home page Failed, please set manually! ");
}
}
//Add to favorites
function AddCollect() {
var url = window.location.href;
try {
window.external.addFavorite(url, " The source of enterprise ");
}
catch (e) {
try {
window.sidebar.addPanel(" The source of enterprise ", url, "");
}
catch (e) {
alert(" Join collection failed, please use Ctrl+D add ");
}
}
}
//#endregion
//#region all selected/none selected
//CheckSelectAll(true);
function CheckSelectAll(check) {
$("input[type='checkbox']").attr("checked", check)
}
//#endregion
//#region verification code countdown
//CountDown("#btnGetCode",60);
function CountDown(item, times) {//The element to manipulate, time (s)
var timer = setInterval(function () {
var btnValidate = $(item);
if (times > 0) {
btnValidate.attr("disabled", "false").css("opacity", "0.5").val(" To obtain (" + times + ")");
times--;
} else {
btnValidate.removeAttr("disabled").css("opacity", "1").val(" Get verification code ");
clearInterval(timer);
}
}, 1000);
}
//#endregion
//#region clears the default value of the text box
//ClearEmpty("#txtName");
function ClearEmpty(obj) {//The element to manipulate
$(obj).focus(function () {
if ($(this).val() == this.defaultValue) {
$(this).val("");
}
}).blur(function () {
if ($(this).val() == "") {
$(this).val(this.defaultValue);
}
});
}
//#endregion
//#region refreshes the page
function Refresh() {
window.parent.location.reload();
}
//#endregion
//#region form validation
//#region check whether it is Chinese
//Var item = checkChinese(" Chinese ");
function checkChinese(obj) {
var reg = /[^u4e00-u9fa5]/;
return !reg.test(obj);
}
//#endregion
//#region checks if it is a number
// var item = checkNum("123");
function checkNum(obj) {
var reg = /^d+$/;
return reg.test(obj);
}
//#endregion
//#region checks for letters
// var item = checkLetter("abc");
function checkLetter(obj) {
var reg = /^[a-zA-Z]+$/;
return reg.test(obj);
}
//#endregion
//#region checks for letters Or digital
// var item = checkLetterNum("abc123");
function checkLetterNum(obj) {
var reg = /^[a-zA-Z0-9]+$/;
return reg.test(obj);
}
//#endregion
//#region checks for letters Or Chinese
// var item = checkLetterNum("abc123");
function checkLetterChina(obj) {
var reg = /^[A-Za-zu4E00-u9FA5]+$/;
return reg.test(obj);
}
//#endregion
//#region checks for letters Or Chinese or Numbers
// var item = checkLetterNum("abc123");
function checkLetterChinaNum(obj) {
var reg = /^[a-zA-Z0-9u4E00-u9FA5]+$/;
return reg.test(obj);
}
//#endregion
//#region checks the phone number format
// var item = checkMobile("13888888888")
function checkMobile(obj) {
var reg = /^[1][3458][0-9]{9}$/;
return reg.test(obj);
}
//#endregion
//#region checks the mailbox format
// var item = checkEmail("abc@123.com")
function checkEmail(obj) {
var reg = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
return reg.test(obj);
}
//#endregion
//#region checks the id card format
// var item = checkIDCard("555555555555555555")
function checkIDCard(obj) {
var reg = /(^d{15}$)|(^d{18}$)|(^d{17}(d|X|x)$)/;
return reg.test(obj);
}
//#endregion
//The random number
function GetRandomNum(Min, Max) {
var Range = Max - Min;
var Rand = Math.random();
return (Min + Math.round(Rand * Range));
}
//#endregion
I believe that this article described the use of javascript for WEB programming has a good reference value.