js常用代码

来源:互联网 发布:疯狂淘宝李涛怎么样 编辑:程序博客网 时间:2024/05/17 18:15

【输出控制台】

console.log()

【计算日期】

var myDate = new Date();
myDate.getYear();        //获取当前年份(2位)
myDate.getFullYear();    //获取完整的年份(4位,1970-????)
myDate.getMonth();       //获取当前月份(0-11,0代表1月)
myDate.getDate();        //获取当前日(1-31)
myDate.getDay();         //获取当前星期X(0-6,0代表星期天)
myDate.getTime();        //获取当前时间(从1970.1.1开始的毫秒数)
myDate.getHours();       //获取当前小时数(0-23)
myDate.getMinutes();     //获取当前分钟数(0-59)
myDate.getSeconds();     //获取当前秒数(0-59)
myDate.getMilliseconds();    //获取当前毫秒数(0-999)
myDate.toLocaleDateString();     //获取当前日期
var mytime=myDate.toLocaleTimeString();     //获取当前时间
myDate.toLocaleString( );        //获取日期与时间


【获取某个元素的值】

var a=document.getElementById("operating_time").value;

【给某个元素赋值】

var b=document.getElementById("operating_time");
b.value=“”abc“”


【替换字符串】

//从字符串'Is this all there is'中剪去'is':
  var str='Is this all there is';


  var subStr=new RegExp('is');//创建正则表达式对象
  var result=str.replace(subStr,"");//把'is'替换为空字符串
  console.log(result);//Is th all there is


  var subStr=new RegExp('is','i');//创建正则表达式对象,不区分大小写
  var result=str.replace(subStr,"");//把'is'替换为空字符串
  console.log(result);//this all there is
    
  var subStr=new RegExp('is','ig');//创建正则表达式对象,不区分大小写,全局查找
  var result=str.replace(subStr,"");//把'is'替换为空字符串
  console.log(result);//th all there 


  var subStr=/is/ig;//直接量法创建正则表达式对象,不区分大小写,全局查找
  var result=str.replace(subStr,"");//把'is'替换为空字符串
  console.log(result);//th all there 


  console.log(str);//Is this all there is 可见replace并不改变原始str;