1. ホーム
  2. javascript

Jsユーティリティ関数集

2022-02-08 05:11:42
<パス

乱数発生装置

Math.random()

整数に変換する

parseInt()

日付時刻関数(変数で呼び出す必要がある)。

var b = new Date(); //現在の時刻を取得します。
b.getTime() //タイムスタンプを取得する
b.getFullYear() //年の取得
b.getMonth() + 1; //月を取得します。
b.getDate() //日付の取得
b.getHours() //時間を取得する
b.getMinutes() //分の取得
b.getSeconds() //秒数の取得
b.getDay() //曜日を取得します。
b.getMilliseconds() //ミリ秒の取得

数学関数(Mathで呼び出す)。

abs(x) は、数値の絶対値を返します。
ceil(x) 小数点以下を切り上げます。
floor(x) 数値を切り捨てます。
round(x) 数値を最も近い整数に丸める。
max(x,y) xとyの最大値を返します。
min(x,y) xとyの最小値を返す。
pow(x,y) はxのy乗を返します。
sqrt(x) は、数値の平方根を返します。
random() は 0 ~ 1 の間の乱数を返します。

文字列関数(変数で呼び出すもの)です。

インデックスオブ

文字列の中で、ある部分文字列が最初に現れるインデックスを返します(左から右へ検索)。一致するものがない場合は、-1を返します。
var index1 = a.indexOf("l");
//index1 = 2

charAt

指定された位置の文字を返します。
var get_char = a.charAt(0);
//get_char = "h"
lastIndexOf
文字列中に部分文字列が最後に出現するインデックス(右から左への検索)、または一致するものがない場合は-1を返します。
var index1 = lastIndexOf('l');
//index1 = 3

一致

文字列が正規表現の内容にマッチするかどうかを調べ、マッチしない場合はnullを返す。
var re = new RegExp(/^Θw+$/);
var is_alpha1 = a.match(re);
//is_alpha1 = "こんにちは"
var is_alpha2 = b.match(re)。
//is_alpha2 = null

部分文字列

開始位置と終了位置を引数として渡された文字列の部分文字列を返します。
var sub_string2 = a.substring(1,4);
//sub_string2 = "ell"。

サブストラ

開始位置と長さで渡された文字列の部分文字列を返します。
var sub_string1 = a.substr(1);
//sub_string1 = "ello"
var sub_string2 = a.substr(1,4);
//sub_string2 = "ello"

置き換える

文字列を置き換えます。最初のパラメータは置き換えられる文字列を表し、2番目のパラメータは置き換えられる文字列を表します。
a.replace("he", "aa")

検索

正規表現のマッチ検索を行います。検索に成功した場合、文字列中のマッチした部分のインデックス値が返されます。そうでない場合は、-1が返されます。
var index1 = a.search(re);
//index1 = 0
var index2 = b.search(re);
//index2 = -1

スプリット

文字列を部分文字列に分割して、文字列の配列にする。
var arr1 = a.split("");
//arr1 = [h,e,l,l,o] です。

長さ

長さ関数は、文字列の長さ(含まれている文字数)を返します。

toLowerCase

文字列全体を小文字に変換します。
var lower_string = a.toLowerCase();
//lower_string = "こんにちは"

toUpperCase

文字列全体を大文字に変換します。
var upper_string = a.toUpperCase();
//upper_string = "HELLO"

1.Jsの日数を合計して新しい日付を得る

 function timestampToTime(timestamp) {
        var date = new Date(timestamp);// timestamp is 10 digits *1000, if timestamp is 13 digits don't multiply by 1000
        var Y = date.getFullYear();
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1):date.getMonth()+1);
        var D = (date.getDate()< 10 ? '0'+date.getDate():date.getDate());
        return Y+"year"+M+"month"+D+"day";
    }


便利なメソッド

2. 現在の日付を取得する(yyyyMMdd形式)

function getNowFormatDate() {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + "year" + month + "month" + strDate + "day";
        $("#time").html(currentdate)
        return currentdate;
    }

function toDecimal(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return;
        }
        f = Math.round(x*100)/100;
        return f;
    }

var digitUppercase = function(n) {
        var fraction = ['angle', 'minute'];
        var digit = [
            'zero', 'one', 'two', 'three', 'four',
            'five', 'land', 'seven', 'eight', 'nine'
        ];
        var unit = [
            ['yuan', 'million', 'billion'],
            ['', 'pick', 'hundred', 'thousand']
        ];
        var head = n < 0 ? 'owe' : '';
        n = Math.abs(n);
        var s = '';
        for (var i = 0; i < fraction.length; i++) {
            s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/zero. /, '');
        }
        s = s || 'whole';
        n = Math.floor(n);
        for (var i = 0; i < unit[0].length && n > 0; i++) {
            var p = '';
            for (var j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[n % 10] + unit[1][j] + p;
                n = Math.floor(n / 10);
            }
            s = p.replace(/(zero.) *zero$/, '').replace(/^$/, 'zero') + unit[0][i] + s;
        }
        return head + s.replace(/(zero.) *zero$/, '$')
                .replace(/(zero.) +/g, 'zero')
                .replace(/^整$/, 'zero dollars whole');
    }


function dataIsNotNull(data) {
        if (data ! = null && typeof(data) ! = "undefined" && data ! = "" && data ! = "''" && data ! = '') {
            return true;
        }
        else {
            return false;
        }
    }

 /* Compare two string times A-B
 * A>B return 1
 * A
$.compareTime = function(time1,time2) {
    if(new Date(time1.replace("-", "/").replace("-", "/")).getTime() > new Date(time2.replace("-", "/")).getTime() > new Date(time2.replace("-", "/")) "-", "/").replace("-", "/")).getTime()) {
        return 1;
    }else if(new Date(time1.replace("-", "/").replace("-", "/")).getTime() < new Date(time2. replace("-", "/").replace("-", "/")).getTime()) {
        return -1;
    }else if(new Date(time1.replace("-", "/").replace("-", "/")).getTime() == new Date(time2.replace( "-", "/").replace("-", "/")).getTime()) {
        return 0;
    }else {
        return 2;
    }
};

function verifyEmailAddress(strEmail){
  var myReg = /^[_a-zA-Z0-9_-_. _-]+@([_a-zA-Z0-9_-]+\.) +[a-zA-Z]{2,3}$/;
  return myReg.test(strEmail);
}

function itIsDate(DateString , Dilimeter) 
{ 
  if (DateString==null) return false; 
  if (Dilimeter=='' || Dilimeter==null) 
   Dilimeter = '-'; 
  var tempy=''; 
  var tempm=''; 
  var tempd=''; 
  var tempArray; 
  if (DateString.length<8 && DateString.length>10) 
    return false;    
  tempArray = DateString.split(Dilimeter); 
  if (tempArray.length!=3) 
   return false; 
  if (tempArray[0].length==4) 
  { 
   tempy = tempArray[0]; 
   tempd = tempArray[2]; 
  } 
  else 
  { 
   tempy = tempArray[2]; 
   tempd = tempArray[1]; 
  } 
  tempm = tempArray[1]; 
  var tDateString = tempy + '/'+tempm + '/'+tempd+' 8:0:0';//add eight hours because we are in the eastern eight 
  var tempDate = new Date(tDateString); 
  if (isNaN(tempDate)) 
   return false; 
 if (((tempDate.getUTCFullYear()).toString()==tempy) && (tempDate.getMonth()==parseInt(tempm)-1) && (tempDate.getDate()= =parseInt(tempd))) 
  { 
   return true; 
  } 
  else 
  { 
   return false; 
  } 
} 

function CheckAll(form){
	var length = form.itemId.length;
	var tocheck = form.chkall.checked;
	if (length)
		for (var i=0; i<length; i++){ 
			if (form.itemId[i].disabled ! = true){
				form.itemId[i].checked = tocheck;
			} 			
		}
	else {
		if (form.itemId.disabled ! =true){
			form.itemId.checked = tocheck;
		}
	}
}

function InputIntNumberCheck(){
	// for IE or Netscape support
	var theEvent=window.event || arguments.callee.caller.arguments[0]; 
	var elm ;
	var ver = navigator.appVersion;
	if (ver.indexOf("MSIE") ! = -1){ // IE
		if ( ! ((theEvent.keyCode >=48)&&(theEvent.keyCode<=57))){
			theEvent.keyCode=0;
		}
	}else{ // Netscape
		if ( ! ((theEvent.which >=48)&&(theEvent.which<=57))){
			theEvent.stopPropagation();
			theEvent.preventDefault();
		}
	}
	//
}


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;"
}

function getCookie(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")));
    if (arr ! = null) return unescape(arr[2]);
    return null
}

function sort(arr, type = 1) {
    return arr.sort((a, b) => {
        switch (type) {
            case 1:
                return a - b;
            case 2:
                return b - a;
            case 3:
                return Math.random() - 0.5;
            default:
                return arr;
        }
    })
}


function cached(fn) {
  let cache = Object.create(null);
  return function cachedFn(str) {
    let hit = cache[str];
    return hit || (cache[str] = fn(str))
  }
}

function getExplorerInfo() {
  let t = navigator.userAgent.toLowerCase();
  return 0 <= t.indexOf("msie") ? { //ie < 11
    type: "IE",
    version: Number(t.match(/msie ([\d]+)/)[1])
  } : ! !t.match(/trident\/. +?rv:(([\d.]+))/) ? { // ie 11
    type: "IE",
    version: 11
  } : 0 <= t.indexOf("edge") ? {
    type: "Edge",
    version: Number(t.match(/edge\/([\d]+)/)[1])
  } : 0 <= t.indexOf("firefox") ? {
    type: "Firefox",
    version: Number(t.match(/firefox\/([\d]+)/)[1])
  } : 0 <= t.indexOf("chrome") ? {
    type: "Chrome",
    version: Number(t.match(/chrome\/([\d]+)/)[1])
  } : 0 <= t.indexOf("opera") ? {
    type: "Opera",
    version: Number(t.match(/opera.([\d]+)/)[1])
  } : 0 <= t.indexOf("Safari") ? {
    type: "Safari",
    version: Number(t.match(/version\/([\d]+)/)[1])
  } : {
    type: t,
    version: -1
  }
}

function unique(arr){
  if(!isArrayLink(arr)){ //not an array-like object
    return arr
  }
  let result = []
  let objarr = []
  let obj = Object.create(null)
   
  arr.forEach(item => {
    if(isStatic(item)){// is the original data except symbol
      let key = item + '_' + getRawType(item);
      if(!obj[key]){
        obj[key] = true
        result.push(item)
      }
    }else{//reference type and symbol
      if(!objarr.includes(item)){
        objarr.push(item)
        result.push(item)
      }
    }
  })
   
  return resulte
}

function downloadFile(filename, data){
  let DownloadLink = document.createElement('a');
 
  if ( DownloadLink ){
    document.body.appendChild(DownloadLink);
    DownloadLink.style = 'display: none';
    DownloadLink.download = filename;
    DownloadLink.href = data;
 
    if ( document.createEvent ){
      let DownloadEvt = document.createEvent('MouseEvents');
 
      DownloadEvt.initEvent('click', true, false);
      DownloadLink.dispatchEvent(DownloadEvt);
    }
    else if ( document.createEventObject )
      DownloadLink.fireEvent('onclick');
    else if (typeof DownloadLink.onclick == 'function' )
      DownloadLink.onclick();
 
    document.body.removeChild(DownloadLink);
  }
}

function toFullScreen(){
  let elem = document.body;
  elem.webkitRequestFullScreen 
  ? elem.webkitRequestFullScreen()
  : elem.mozRequestFullScreen
  ? elem.mozRequestFullScreen()
  : elem.msRequestFullscreen
  ? elem.msRequestFullscreen()
  : elem.requestFullScreen
  ? elem.requestFullScreen()
  : alert("Browser does not support full screen");
}

function toFullScreen(){
  let elem = document.body;
  elem.webkitRequestFullScreen 
  ? elem.webkitRequestFullScreen()
  : elem.mozRequestFullScreen
  ? elem.mozRequestFullScreen()
  : elem.msRequestFullscreen
  ? elem.msRequestFullscreen()
  : elem.requestFullScreen
  ? elem.requestFullScreen()
  : alert("Browser does not support full screen");
}

function max(arr){
  arr = arr.filter(item => ! _isNaN(item))
  return arr.length ? Math.max.apply(null, arr) : undefined
}
//max([1, 2, '11', null, 'fdf', []]) ==> 11

function min(arr){
  arr = arr.filter(item => ! _isNaN(item))
  return arr.length ? Math.min.apply(null, arr) : undefined
}
//min([1, 2, '11', null, 'fdf', []]) ==> 1

function isNumber(val){
    var regPos = /^\d+(\. \d+)? $/; //non-negative floating point number
    var regNeg = /^(-(([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
    if(regPos.test(val) || regNeg.test(val)){
        return true;
    }else{
        return false;
    }
}

function hasRepeatValue(a) {
        return /(\x0f[^\x0f]+)\x0f[\s\S]*\1/.test("\x0f" + a.join("\x0f\x0f") + "\x0f");
}


function getIdcardData(){
   var ido=document.getElementById('idCardNumberHandle');//ID of the ID card number input element
   var bd=document.getElementById('birthdayHandle');
   var sex=document.getElementById('sexHandle');
   if(! /^\d{6}((? :19|20)((? :\d{2}(? :0[13578]|1[02])(? :0[1-9]|[12]\d|3[01]))|(? :\d{2}(? :0[13456789]|1[012])(? :0[1-9]|[12]\d|30))|(? :\d{2}02(? :0[1-9]|1\d|2[0-8]))|(? :(? :0[48]|[2468][048]|[13579][26])0229)))\d{2}(\d)[xX\d]$/.test(ido.value)){
      alert('ID number is illegal.') ;
      return;
   }
   bd.value=(RegExp.$1).substr(0,4)+'-'+(RegExp.$1).substr(4,2)+'-'+(RegExp.$1).substr(6,2);//set date of birth
   ex.value=(parseInt(ido.value.charAt(ido.value.length-2))%2==0?'female':'male');//set the gender
}

function insertAfter(newElement,targetElement){
  var parent = targetElement.parentNode;
  if (parent.lastChild == targetElement) {
    parent.appendChild(newElement);
  } else {
    parent.insertBefore(newElement,targetElement.nextSubling)
  }
}

var getURLParam = function(name) {
    return decodeURIComponent((new RegExp('[? |&]' + name + '=' + '([^&;]+?) (&|#|;|$)', "ig").exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
};

function cloneObj(obj) {
    var o = obj.constructor == Object ? new obj.constructor() : new obj.constructor(obj.valueOf());
    for(var key in obj){
        if(o[key] ! = obj[key] ){
            if(typeof(obj[key]) == 'object' ){
                o[key] = mods.cloneObj(obj[key]);
            }else{
                o[key] = obj[key];
            }
        }
    }
    return o;
}

function randombetween(min, max){
    return min + (Math.random() * (max-min + 1));
}

function browserRedirect() {
                var sUserAgent = navigator.userAgent.toLowerCase();
                var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
                var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
                var bIsMidp = sUserAgent.match(/midp/i) == "midp";
                var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
                var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
                var bIsAndroid = sUserAgent.match(/android/i) == "android";
                var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
                var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
                if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {               
                    // Mobile
                } else {        
                    //pc side
                    $('*').css("width",'100%');  
                    $('*').css("height",'100%');  
                }
            }
            browserRedirect(); // determine if it's mobile or pc
            $(function(){
                var h = window.screen.height;
                var w = window.screen.width;
                $('#myiframe').attr("width",w); //append the width attribute to it
                $('#myiframe').attr("height",h); //append the height attribute to it
            })

// Calculate age
    function getAge(strBirthday) {
        var a = /^(\d{4})-(\d{2})-(\d{2})$/
        if (a.test(strBirthday)) {
            var birthYear = strBirthday.substring(0, 4);
            var year = new Date();
            var Nyear = year.getFullYear();
            var Nage = Nyear - birthYear;
            if (Nage <= 0) {
                Nage = 1;
            }
            return Nage;//return age
        } else {
            return "";
        }
    }

//BMI calculation
    function getBMI(w, h) {
        h = h * 0.01;
        var bmi = (w / (h * h)).toFixed(4);
        return bmi;
    }

 //body area calculation
    function getBodyArea(w, h) {
        var bodyArea = (0.0061 * h + 0.0128 * w - 0.1529).toFixed(4);
        return bodyArea;
    }


 //Get the date of birth and the corresponding age based on the ID
                        $("#idNumber").on("blur", function () {
                            var num = Number($("#idNumber").val().split("").slice(6, 10).join(""))
                            var mon = $("#idNumber").val().substring(10, 12)
                            var da = $("#idNumber").val().substring(12, 14)
                            var birth = num + "/" + mon + "/" + da
                            var dt = new Date()
                            var year = dt.getFullYear()
                            $("#birthday").val(birth)
                            $("#age").text(year - num)
                        })

function isNumber(val) {
        var regPos = /^\d+(\. \d+)? $/;//non-negative floating point number
        var regNeg = /^(-(([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
        if(regPos.test(val) || regNeg.test(val)) {
            return true;
        }else {
            return false;
        }
    }

//returns the last seven days of the date
    function getday2() {
        var days = [];
        var date = new Date();
        for(var i=0; i<=144;i+=24){ //144 is the number of hours in the previous six days
            var dateItem = new Date(date.getTime() - i * 60 * 60 * 1000); //use the day's timestamp minus the previous time in milliseconds (hours * minutes * seconds * milliseconds)
            var y = dateItem.getFullYear(); //get the year
            var m = dateItem.getMonth() + 1; //get month js month starts from 0 and needs to be +1
            var d = dateItem.getDate(); //get the date
            m = addDate0(m); //give the odd number of months to fill in the zero
            d = addDate0(d); //add zero to odd numbered dates
            var valueItem= y + '-' + m + '-' + d; //combine
            days.push(valueItem); //add to the array
        }
        console.log('Last seven days:',days);

        return days;
    }

    //add 0 to the date
    function addDate0(time) {
        if (time.toString().length == 1) {
            time = '0' + time.toString();
        }
        return time;
    }

//returns the last seven days of the date
    function getday2() {
        var days = [];
        var date = new Date();
        for(var i=0; i<=144;i+=24){ //144 is the number of hours in the previous six days
            var dateItem = new Date(date.getTime() + i * 60 * 60 * 1000); //use the day's timestamp minus the previous time milliseconds (hours * minutes * seconds * milliseconds)
            var y = dateItem.getFullYear(); //get the year
            var m = dateItem.getMonth() + 1; //get month js month starts from 0 and needs to be +1
            var d = dateItem.getDate(); //get the date
            m = addDate0(m); //give the odd number of months to fill in the zero
            d = addDate0(d); //add zero to odd numbered dates
            var valueItem= y + '-' + m + '-' + d; //combine
            days.push(valueItem); //add to the array
        }
        console.log('Last seven days:',days);

        return days;
    }

    //add 0 to the date
    function addDate0(time) {
        if (time.toString().length == 1) {
            time = '0' + time.toString();
        }
        return time;
    }


3. 丸め方

function toDecimal(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return;
        }
        f = Math.round(x*100)/100;
        return f;
    }


4.数字を中国の大文字に変換するJs

var digitUppercase = function(n) {
        var fraction = ['angle', 'minute'];
        var digit = [
            'zero', 'one', 'two', 'three', 'four',
            'five', 'land', 'seven', 'eight', 'nine'
        ];
        var unit = [
            ['yuan', 'million', 'billion'],
            ['', 'pick', 'hundred', 'thousand']
        ];
        var head = n < 0 ? 'owe' : '';
        n = Math.abs(n);
        var s = '';
        for (var i = 0; i < fraction.length; i++) {
            s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/zero. /, '');
        }
        s = s || 'whole';
        n = Math.floor(n);
        for (var i = 0; i < unit[0].length && n > 0; i++) {
            var p = '';
            for (var j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[n % 10] + unit[1][j] + p;
                n = Math.floor(n / 10);
            }
            s = p.replace(/(zero.) *zero$/, '').replace(/^$/, 'zero') + unit[0][i] + s;
        }
        return head + s.replace(/(zero.) *zero$/, '$')
                .replace(/(zero.) +/g, 'zero')
                .replace(/^整$/, 'zero dollars whole');
    }



5. データが空かどうかを判断する

function dataIsNotNull(data) {
        if (data ! = null && typeof(data) ! = "undefined" && data ! = "" && data ! = "''" && data ! = '') {
            return true;
        }
        else {
            return false;
        }
    }


6. 文字列の日付比較

 /* Compare two string times A-B
 * A>B return 1
 * A
$.compareTime = function(time1,time2) {
    if(new Date(time1.replace("-", "/").replace("-", "/")).getTime() > new Date(time2.replace("-", "/")).getTime() > new Date(time2.replace("-", "/")) "-", "/").replace("-", "/")).getTime()) {
        return 1;
    }else if(new Date(time1.replace("-", "/").replace("-", "/")).getTime() < new Date(time2. replace("-", "/").replace("-", "/")).getTime()) {
        return -1;
    }else if(new Date(time1.replace("-", "/").replace("-", "/")).getTime() == new Date(time2.replace( "-", "/").replace("-", "/")).getTime()) {
        return 0;
    }else {
        return 2;
    }
};


7. メールを確認する

function verifyEmailAddress(strEmail){
  var myReg = /^[_a-zA-Z0-9_-_. _-]+@([_a-zA-Z0-9_-]+\.) +[a-zA-Z]{2,3}$/;
  return myReg.test(strEmail);
}


8. 日付データかどうかの判断

function itIsDate(DateString , Dilimeter) 
{ 
  if (DateString==null) return false; 
  if (Dilimeter=='' || Dilimeter==null) 
   Dilimeter = '-'; 
  var tempy=''; 
  var tempm=''; 
  var tempd=''; 
  var tempArray; 
  if (DateString.length<8 && DateString.length>10) 
    return false;    
  tempArray = DateString.split(Dilimeter); 
  if (tempArray.length!=3) 
   return false; 
  if (tempArray[0].length==4) 
  { 
   tempy = tempArray[0]; 
   tempd = tempArray[2]; 
  } 
  else 
  { 
   tempy = tempArray[2]; 
   tempd = tempArray[1]; 
  } 
  tempm = tempArray[1]; 
  var tDateString = tempy + '/'+tempm + '/'+tempd+' 8:0:0';//add eight hours because we are in the eastern eight 
  var tempDate = new Date(tDateString); 
  if (isNaN(tempDate)) 
   return false; 
 if (((tempDate.getUTCFullYear()).toString()==tempy) && (tempDate.getMonth()==parseInt(tempm)-1) && (tempDate.getDate()= =parseInt(tempd))) 
  { 
   return true; 
  } 
  else 
  { 
   return false; 
  } 
} 


9. チェックボックスチェックオール&アンチェック

function CheckAll(form){
	var length = form.itemId.length;
	var tocheck = form.chkall.checked;
	if (length)
		for (var i=0; i<length; i++){ 
			if (form.itemId[i].disabled ! = true){
				form.itemId[i].checked = tocheck;
			} 			
		}
	else {
		if (form.itemId.disabled ! =true){
			form.itemId.checked = tocheck;
		}
	}
}


10. デジタル入力制御

function InputIntNumberCheck(){
	// for IE or Netscape support
	var theEvent=window.event || arguments.callee.caller.arguments[0]; 
	var elm ;
	var ver = navigator.appVersion;
	if (ver.indexOf("MSIE") ! = -1){ // IE
		if ( ! ((theEvent.keyCode >=48)&&(theEvent.keyCode<=57))){
			theEvent.keyCode=0;
		}
	}else{ // Netscape
		if ( ! ((theEvent.which >=48)&&(theEvent.which<=57))){
			theEvent.stopPropagation();
			theEvent.preventDefault();
		}
	}
	//
}


11. Cookieの設定と取得


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;"
}


function getCookie(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")));
    if (arr ! = null) return unescape(arr[2]);
    return null
}


12. データの並べ替え

function sort(arr, type = 1) {
    return arr.sort((a, b) => {
        switch (type) {
            case 1:
                return a - b;
            case 2:
                return b - a;
            case 3:
                return Math.random() - 0.5;
            default:
                return arr;
        }
    })
}



13. メモリー機能(関数操作の結果をキャッシュする)

function cached(fn) {
  let cache = Object.create(null);
  return function cachedFn(str) {
    let hit = cache[str];
    return hit || (cache[str] = fn(str))
  }
}


14. ブラウザ情報取得

function getExplorerInfo() {
  let t = navigator.userAgent.toLowerCase();
  return 0 <= t.indexOf("msie") ? { //ie < 11
    type: "IE",
    version: Number(t.match(/msie ([\d]+)/)[1])
  } : ! !t.match(/trident\/. +?rv:(([\d.]+))/) ? { // ie 11
    type: "IE",
    version: 11
  } : 0 <= t.indexOf("edge") ? {
    type: "Edge",
    version: Number(t.match(/edge\/([\d]+)/)[1])
  } : 0 <= t.indexOf("firefox") ? {
    type: "Firefox",
    version: Number(t.match(/firefox\/([\d]+)/)[1])
  } : 0 <= t.indexOf("chrome") ? {
    type: "Chrome",
    version: Number(t.match(/chrome\/([\d]+)/)[1])
  } : 0 <= t.indexOf("opera") ? {
    type: "Opera",
    version: Number(t.match(/opera.([\d]+)/)[1])
  } : 0 <= t.indexOf("Safari") ? {
    type: "Safari",
    version: Number(t.match(/version\/([\d]+)/)[1])
  } : {
    type: t,
    version: -1
  }
}


15. 配列の重複排除 新しい配列を返す

function unique(arr){
  if(!isArrayLink(arr)){ //not an array-like object
    return arr
  }
  let result = []
  let objarr = []
  let obj = Object.create(null)
   
  arr.forEach(item => {
    if(isStatic(item)){// is the original data except symbol
      let key = item + '_' + getRawType(item);
      if(!obj[key]){
        obj[key] = true
        result.push(item)
      }
    }else{//reference type and symbol
      if(!objarr.includes(item)){
        objarr.push(item)
        result.push(item)
      }
    }
  })
   
  return resulte
}


16.Base64データエクスポートファイル ファイルダウンロード

function downloadFile(filename, data){
  let DownloadLink = document.createElement('a');
 
  if ( DownloadLink ){
    document.body.appendChild(DownloadLink);
    DownloadLink.style = 'display: none';
    DownloadLink.download = filename;
    DownloadLink.href = data;
 
    if ( document.createEvent ){
      let DownloadEvt = document.createEvent('MouseEvents');
 
      DownloadEvt.initEvent('click', true, false);
      DownloadLink.dispatchEvent(DownloadEvt);
    }
    else if ( document.createEventObject )
      DownloadLink.fireEvent('onclick');
    else if (typeof DownloadLink.onclick == 'function' )
      DownloadLink.onclick();
 
    document.body.removeChild(DownloadLink);
  }
}


17. フルスクリーン

function toFullScreen(){
  let elem = document.body;
  elem.webkitRequestFullScreen 
  ? elem.webkitRequestFullScreen()
  : elem.mozRequestFullScreen
  ? elem.mozRequestFullScreen()
  : elem.msRequestFullscreen
  ? elem.msRequestFullscreen()
  : elem.requestFullScreen
  ? elem.requestFullScreen()
  : alert("Browser does not support full screen");
}


18. フルスクリーンを終了する

function toFullScreen(){
  let elem = document.body;
  elem.webkitRequestFullScreen 
  ? elem.webkitRequestFullScreen()
  : elem.mozRequestFullScreen
  ? elem.mozRequestFullScreen()
  : elem.msRequestFullscreen
  ? elem.msRequestFullscreen()
  : elem.requestFullScreen
  ? elem.requestFullScreen()
  : alert("Browser does not support full screen");
}


19. 配列中のNaNでない値の最大値を求めよ

function max(arr){
  arr = arr.filter(item => ! _isNaN(item))
  return arr.length ? Math.max.apply(null, arr) : undefined
}
//max([1, 2, '11', null, 'fdf', []]) ==> 11


20. 配列の中でNaNでない値の最小値を求めよ

function min(arr){
  arr = arr.filter(item => ! _isNaN(item))
  return arr.length ? Math.min.apply(null, arr) : undefined
}
//min([1, 2, '11', null, 'fdf', []]) ==> 1


21. 規則性のある数値の検証

function isNumber(val){
    var regPos = /^\d+(\. \d+)? $/; //non-negative floating point number
    var regNeg = /^(-(([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
    if(regPos.test(val) || regNeg.test(val)){
        return true;
    }else{
        return false;
    }
}


22.配列の要素の重複を検証する

function hasRepeatValue(a) {
        return /(\x0f[^\x0f]+)\x0f[\s\S]*\1/.test("\x0f" + a.join("\x0f\x0f") + "\x0f");
}



23. IDカードから性別と生年月日情報を抽出する(ID番号 下一桁が性別、奇数が男性、偶数が女性)。

function getIdcardData(){
   var ido=document.getElementById('idCardNumberHandle');//ID of the ID card number input element
   var bd=document.getElementById('birthdayHandle');
   var sex=document.getElementById('sexHandle');
   if(! /^\d{6}((? :19|20)((? :\d{2}(? :0[13578]|1[02])(? :0[1-9]|[12]\d|3[01]))|(? :\d{2}(? :0[13456789]|1[012])(? :0[1-9]|[12]\d|30))|(? :\d{2}02(? :0[1-9]|1\d|2[0-8]))|(? :(? :0[48]|[2468][048]|[13579][26])0229)))\d{2}(\d)[xX\d]$/.test(ido.value)){
      alert('ID number is illegal.') ;
      return;
   }
   bd.value=(RegExp.$1).substr(0,4)+'-'+(RegExp.$1).substr(4,2)+'-'+(RegExp.$1).substr(6,2);//set date of birth
   ex.value=(parseInt(ido.value.charAt(ido.value.length-2))%2==0?'female':'male');//set the gender
}


24. 既存の要素の後に新しい要素を挿入する

function insertAfter(newElement,targetElement){
  var parent = targetElement.parentNode;
  if (parent.lastChild == targetElement) {
    parent.appendChild(newElement);
  } else {
    parent.insertBefore(newElement,targetElement.nextSubling)
  }
}


25. ブラウザのurlでパラメータの値を取得する

var getURLParam = function(name) {
    return decodeURIComponent((new RegExp('[? |&]' + name + '=' + '([^&;]+?) (&|#|;|$)', "ig").exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
};


26. ディープコピーオブジェクト

function cloneObj(obj) {
    var o = obj.constructor == Object ? new obj.constructor() : new obj.constructor(obj.valueOf());
    for(var key in obj){
        if(o[key] ! = obj[key] ){
            if(typeof(obj[key]) == 'object' ){
                o[key] = mods.cloneObj(obj[key]);
            }else{
                o[key] = obj[key];
            }
        }
    }
    return o;
}


27. 乱数の生成

function randombetween(min, max){
    return min + (Math.random() * (max-min + 1));
}


28. モバイルかpcかを判断する

function browserRedirect() {
                var sUserAgent = navigator.userAgent.toLowerCase();
                var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
                var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
                var bIsMidp = sUserAgent.match(/midp/i) == "midp";
                var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
                var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
                var bIsAndroid = sUserAgent.match(/android/i) == "android";
                var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
                var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
                if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {               
                    // Mobile
                } else {        
                    //pc side
                    $('*').css("width",'100%');  
                    $('*').css("height",'100%');  
                }
            }
            browserRedirect(); // determine if it's mobile or pc
            $(function(){
                var h = window.screen.height;
                var w = window.screen.width;
                $('#myiframe').attr("width",w); //append the width attribute to it
                $('#myiframe').attr("height",h); //append the height attribute to it
            })


29. 生年月日から年齢を計算する

// Calculate age
    function getAge(strBirthday) {
        var a = /^(\d{4})-(\d{2})-(\d{2})$/
        if (a.test(strBirthday)) {
            var birthYear = strBirthday.substring(0, 4);
            var year = new Date();
            var Nyear = year.getFullYear();
            var Nage = Nyear - birthYear;
            if (Nage <= 0) {
                Nage = 1;
            }
            return Nage;//return age
        } else {
            return "";
        }
    }


30. BMI計算

//BMI calculation
    function getBMI(w, h) {
        h = h * 0.01;
        var bmi = (w / (h * h)).toFixed(4);
        return bmi;
    }


31. 体表面積の計算

 //body area calculation
    function getBodyArea(w, h) {
        var bodyArea = (0.0061 * h + 0.0128 * w - 0.1529).toFixed(4);
        return bodyArea;
    }



32.IDから生年月日と年齢を取得する

 //Get the date of birth and the corresponding age based on the ID
                        $("#idNumber").on("blur", function () {
                            var num = Number($("#idNumber").val().split("").slice(6, 10).join(""))
                            var mon = $("#idNumber").val().substring(10, 12)
                            var da = $("#idNumber").val().substring(12, 14)
                            var birth = num + "/" + mon + "/" + da
                            var dt = new Date()
                            var year = dt.getFullYear()
                            $("#birthday").val(birth)
                            $("#age").text(year - num)
                        })


33. 文字列が数字かどうかを判定する

function isNumber(val) {
        var regPos = /^\d+(\. \d+)? $/;//non-negative floating point number
        var regNeg = /^(-(([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
        if(regPos.test(val) || regNeg.test(val)) {
            return true;
        }else {
            return false;
        }
    }


34.過去7日間を問い合わせる(過去7日間現在の日付2021-10-13)

//returns the last seven days of the date
    function getday2() {
        var days = [];
        var date = new Date();
        for(var i=0; i<=144;i+=24){ //144 is the number of hours in the previous six days
            var dateItem = new Date(date.getTime() - i * 60 * 60 * 1000); //use the day's timestamp minus the previous time in milliseconds (hours * minutes * seconds * milliseconds)
            var y = dateItem.getFullYear(); //get the year
            var m = dateItem.getMonth() + 1; //get month js month starts from 0 and needs to be +1
            var d = dateItem.getDate(); //get the date
            m = addDate0(m); //give the odd number of months to fill in the zero
            d = addDate0(d); //add zero to odd numbered dates
            var valueItem= y + '-' + m + '-' + d; //combine
            days.push(valueItem); //add to the array
        }
        console.log('Last seven days:',days);

        return days;
    }

    //add 0 to the date
    function addDate0(time) {
        if (time.toString().length == 1) {
            time = '0' + time.toString();
        }
        return time;
    }


35.過去7日間を照会する(過去7日間 現在の日付 2021-10-13)

//returns the last seven days of the date
    function getday2() {
        var days = [];
        var date = new Date();
        for(var i=0; i<=144;i+=24){ //144 is the number of hours in the previous six days
            var dateItem = new Date(date.getTime() + i * 60 * 60 * 1000); //use the day's timestamp minus the previous time milliseconds (hours * minutes * seconds * milliseconds)
            var y = dateItem.getFullYear(); //get the year
            var m = dateItem.getMonth() + 1; //get month js month starts from 0 and needs to be +1
            var d = dateItem.getDate(); //get the date
            m = addDate0(m); //give the odd number of months to fill in the zero
            d = addDate0(d); //add zero to odd numbered dates
            var valueItem= y + '-' + m + '-' + d; //combine
            days.push(valueItem); //add to the array
        }
        console.log('Last seven days:',days);

        return days;
    }

    //add 0 to the date
    function addDate0(time) {
        if (time.toString().length == 1) {
            time = '0' + time.toString();
        }
        return time;
    }


よく使われるイベントを整理しました

データ共有

600組み込みJavaScriptの例 必要に応じてプライベートメッセージまたはコメント(下の画像は一部のみ表示されています)