Home Web Front-end JS Tutorial Summary of common javascript operations_javascript skills

Summary of common javascript operations_javascript skills

May 16, 2016 pm 04:37 PM
javascript common operate

本文整理汇总了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

Copy after login

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

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PyCharm usage tutorial: guide you in detail to run the operation PyCharm usage tutorial: guide you in detail to run the operation Feb 26, 2024 pm 05:51 PM

PyCharm is a very popular Python integrated development environment (IDE). It provides a wealth of functions and tools to make Python development more efficient and convenient. This article will introduce you to the basic operation methods of PyCharm and provide specific code examples to help readers quickly get started and become proficient in operating the tool. 1. Download and install PyCharm First, we need to go to the PyCharm official website (https://www.jetbrains.com/pyc

What is sudo and why is it important? What is sudo and why is it important? Feb 21, 2024 pm 07:01 PM

sudo (superuser execution) is a key command in Linux and Unix systems that allows ordinary users to run specific commands with root privileges. The function of sudo is mainly reflected in the following aspects: Providing permission control: sudo achieves strict control over system resources and sensitive operations by authorizing users to temporarily obtain superuser permissions. Ordinary users can only obtain temporary privileges through sudo when needed, and do not need to log in as superuser all the time. Improved security: By using sudo, you can avoid using the root account during routine operations. Using the root account for all operations may lead to unexpected system damage, as any mistaken or careless operation will have full permissions. and

Linux Deploy operation steps and precautions Linux Deploy operation steps and precautions Mar 14, 2024 pm 03:03 PM

LinuxDeploy operating steps and precautions LinuxDeploy is a powerful tool that can help users quickly deploy various Linux distributions on Android devices, allowing users to experience a complete Linux system on their mobile devices. This article will introduce the operating steps and precautions of LinuxDeploy in detail, and provide specific code examples to help readers better use this tool. Operation steps: Install LinuxDeploy: First, install

What to do if you forget to press F2 for win10 boot password What to do if you forget to press F2 for win10 boot password Feb 28, 2024 am 08:31 AM

Presumably many users have several unused computers at home, and they have completely forgotten the power-on password because they have not been used for a long time, so they would like to know what to do if they forget the password? Then let’s take a look together. What to do if you forget to press F2 for win10 boot password? 1. Press the power button of the computer, and then press F2 when turning on the computer (different computer brands have different buttons to enter the BIOS). 2. In the bios interface, find the security option (the location may be different for different brands of computers). Usually in the settings menu at the top. 3. Then find the SupervisorPassword option and click it. 4. At this time, the user can see his password, and at the same time find the Enabled next to it and switch it to Dis.

Huawei Mate60 Pro screenshot operation steps sharing Huawei Mate60 Pro screenshot operation steps sharing Mar 23, 2024 am 11:15 AM

With the popularity of smartphones, the screenshot function has become one of the essential skills for daily use of mobile phones. As one of Huawei's flagship mobile phones, Huawei Mate60Pro's screenshot function has naturally attracted much attention from users. Today, we will share the screenshot operation steps of Huawei Mate60Pro mobile phone, so that everyone can take screenshots more conveniently. First of all, Huawei Mate60Pro mobile phone provides a variety of screenshot methods, and you can choose the method that suits you according to your personal habits. The following is a detailed introduction to several commonly used interceptions:

PHP PDO Tutorial: An Advanced Guide from Basics to Mastery PHP PDO Tutorial: An Advanced Guide from Basics to Mastery Feb 19, 2024 pm 06:30 PM

1. Introduction to PDO PDO is an extension library of PHP, which provides an object-oriented way to operate the database. PDO supports a variety of databases, including Mysql, postgresql, oracle, SQLServer, etc. PDO enables developers to use a unified API to operate different databases, which allows developers to easily switch between different databases. 2. PDO connects to the database. To use PDO to connect to the database, you first need to create a PDO object. The constructor of the PDO object receives three parameters: database type, host name, database username and password. For example, the following code creates an object that connects to a mysql database: $dsn="mysq

PHP string manipulation: a practical way to effectively remove spaces PHP string manipulation: a practical way to effectively remove spaces Mar 24, 2024 am 11:45 AM

PHP String Operation: A Practical Method to Effectively Remove Spaces In PHP development, you often encounter situations where you need to remove spaces from a string. Removing spaces can make the string cleaner and facilitate subsequent data processing and display. This article will introduce several effective and practical methods for removing spaces, and attach specific code examples. Method 1: Use the PHP built-in function trim(). The PHP built-in function trim() can remove spaces at both ends of the string (including spaces, tabs, newlines, etc.). It is very convenient and easy to use.

How to bind WeChat on Ele.me How to bind WeChat on Ele.me Apr 01, 2024 pm 03:46 PM

Ele.me is a software that brings together a variety of different delicacies. You can choose and place an order online. The merchant will make it immediately after receiving the order. Users can bind WeChat through the software. If you want to know the specific operation method , remember to check out the PHP Chinese website. Instructions on how to bind WeChat to Ele.me: 1. First open the Ele.me software. After entering the homepage, we click [My] in the lower right corner; 2. Then in the My page, we need to click [Account] in the upper left corner; 3. Then come to the personal information page where we can bind mobile phones, WeChat, Alipay, and Taobao. Here we click [WeChat]; 4. After the final click, select the WeChat account that needs to be bound in the WeChat authorization page and click Just [Allow];

See all articles