search
HomeWeb Front-endJS TutorialSummary of common javascript operations_javascript skills

本文整理汇总了javascript常见的各类操作,包括字符串、时间、表单、正则验证等等。有着极高的参考价值。分享给大家供大家参考之用。具体方法如下:

/***** BasePage.js 公共的 脚本文件 部分方法需引用jquery库 *****/
 
//#region 日期操作
 
//字符串转化为时间。
function stringtoTime(date1) {
  var dt = new Date(Date.parse(date1.replace(/-/g, "/")));
  return dt;
}
 
// 使用 var date1 = "2013-06-08 15:23:31"或"2013/6/8 9:9:00"格式;
//-------------------------------------------------------------
// 日期格式化
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;
}
 
////使用方法 
 
//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)
////使用方法2: 
//var testDate = new Date();
//var testStr = testDate.format("yyyy年MM月dd日hh小时mm分ss秒");
////示例: 
//alert(testDate.format("yyyy年MM月dd日"));
//-------------------------------------------------------------
//设置周期内的日期(数组)
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
 
//日期加上天数后的新日期.
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() + "年" + (nd.getMonth() + 1) + "月" + 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;
}

//两个日期的差值(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操作
 
/*
* 根据QueryString参数名称获取值
*/
function getQueryStringByName(name) {
  var result = location.search.match(new RegExp("[\&#63;\&]" + name + "=([^\&]+)", "i"));
  if (result == null || result.length < 1)
    return "";
 
  return result[1];
}
 
function GetQueryString(name) {
  // 如果链接没有参数,或者链接中不存在我们要获取的参数,直接返回空
  if (location.href.indexOf("&#63;") == -1 || location.href.indexOf(name + '=') == -1) {
    return '';
  }
 
  // 获取链接中参数部分
  var queryString = location.href.substring(location.href.indexOf("&#63;") + 1);
 
  // 分离参数对 &#63;key=value&key2=value2
  var parameters = queryString.split("&");
 
  var pos, paraName, paraValue;
  for (var i = 0; i < parameters.length; i++) {
    // 获取等号位置
    pos = parameters[i].indexOf('=');
    if (pos == -1) {
      continue;
    }
    // 获取name 和 value
    paraName = parameters[i].substring(0, pos);
    paraValue = parameters[i].substring(pos + 1);
    // 如果查询的name等于当前name,就返回当前值,同时,将链接中的+号还原成空格
    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 字符串操作
 
/*
* 截取指定长度字符串
* 参数:
*   strString: 需要截取的字符串
*   strStart: 开始的索引
*   intLen:  截取的长度
*/
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 {
      //长度越界,返回原始数据
      return strString;
    }
  } else return "";
}
 
/*
* 截取指定指定区间的字符串
* 参数:
*   strString: 需要截取的字符串
*   intStart: 开始的索引
*   intEnd:  结束的索引
*/
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 {
      //长度越界,返回原始数据
      return strString;
    }
  } else return "";
}
 
//#endregion
 
//#region 设为首页,添加收藏
 
//设为首页
function SetHome() {
  if (document.all) {
    document.body.style.behavior = "url(#default#homepage)";
    var url = window.location.href;
    document.body.setHomePage(url);
  } else {
    alert("设为首页失败,请手动设置!");
  }
}
 
//添加到收藏
function AddCollect() {
  var url = window.location.href;
  try {
    window.external.addFavorite(url, "美源金业");
  }
  catch (e) {
    try {
      window.sidebar.addPanel("美源金业", url, "");
    }
    catch (e) {
      alert("加入收藏失败,请使用Ctrl+D进行添加");
    }
  }
}
 
//#endregion 
 
//#region 全选/全不选
 
//CheckSelectAll(true);
 
function CheckSelectAll(check) {
  $("input[type='checkbox']").attr("checked", check)
}
 
//#endregion
 
//#region 验证码倒计时
 
//CountDown("#btnGetCode",60);
 
function CountDown(item, times) {//要操作的元素,时间(s)
  var timer = setInterval(function () {
    var btnValidate = $(item);
    if (times > 0) {
      btnValidate.attr("disabled", "false").css("opacity", "0.5").val("重新获取(" + times + ")");
      times--;
    } else {
      btnValidate.removeAttr("disabled").css("opacity", "1").val("获取验证码");
      clearInterval(timer);
    }
  }, 1000);
}
 
//#endregion
 
//#region 清除文本框默认值
 
//ClearEmpty("#txtName");
 
function ClearEmpty(obj) {//要操作的元素
  $(obj).focus(function () {
    if ($(this).val() == this.defaultValue) {
      $(this).val("");
    }
  }).blur(function () {
    if ($(this).val() == "") {
      $(this).val(this.defaultValue);
    }
  });
}
 
//#endregion
 
//#region 刷新页面
 
function Refresh() {
  window.parent.location.reload();
}
 
//#endregion
 
//#region 表单验证
 
//#region 检查是否为中文
 
// var item = checkChinese("中文");
 
function checkChinese(obj) {
  var reg = /[^\u4e00-\u9fa5]/;
  return !reg.test(obj);
}
 
//#endregion
 
//#region 检查是否为数字
 
// var item = checkNum("123");
 
function checkNum(obj) {
  var reg = /^\d+$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查是否为字母
 
// var item = checkLetter("abc");
 
function checkLetter(obj) {
  var reg = /^[a-zA-Z]+$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查是否为字母或数字
 
// var item = checkLetterNum("abc123");
 
function checkLetterNum(obj) {
  var reg = /^[a-zA-Z0-9]+$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查是否为字母或中文
 
// var item = checkLetterNum("abc123");
 
function checkLetterChina(obj) {
  var reg = /^[A-Za-z\u4E00-\u9FA5]+$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查是否为字母或中文或数字
 
// var item = checkLetterNum("abc123");
 
function checkLetterChinaNum(obj) {
  var reg = /^[a-zA-Z0-9\u4E00-\u9FA5]+$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查手机号码格式
 
// var item = checkMobile("13888888888")
 
function checkMobile(obj) {
  var reg = /^[1][3458][0-9]{9}$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查邮箱格式
 
// 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 检查身份证格式
 
// var item = checkIDCard("555555555555555555")
 
function checkIDCard(obj) {
  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return reg.test(obj);
}
 
//#endregion
 
//随机数
function GetRandomNum(Min, Max) {
  var Range = Max - Min;
  var Rand = Math.random();
  return (Min + Math.round(Rand * Range));
} 
 
//#endregion

相信本文所述对大家运用javascript进行WEB程序设计有不错的借鉴价值。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

20+道必知必会的Vue面试题(附答案解析)20+道必知必会的Vue面试题(附答案解析)Apr 06, 2021 am 09:41 AM

本篇文章整理了20+Vue面试题分享给大家,同时附上答案解析。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),