其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

收集一些不错的javascript函数(常用javascript函数收藏)

GG网络技术分享 2025-03-18 16:17 0


javascript一个很酷的变成语言,在做模版时以及后台一些功能时,我们都会用到javascript来实现一些功能,比如页面特效、数据提交、数据获取等,这里蓝叶收集一些不错的javascript函数,以便需要时直接复制使用,为了方便自己记录下常用javascript函数收藏,持续更新中。


//检查字符串是否为有效的json

const isValidJSON = str => {

try {

JSON.parse(str);

return true;

} catch (e) {

return false;

}

};

isValidJSON(\'{\"name\":\"tntweb\",\"age\":20}\'); // true

isValidJSON(\'{\"name\":\"tntweb\",age:\"20\"}\'); // false

isValidJSON(null); // true

//随机获取数组中元素

const randomly = arr => arr[Math.floor(Math.random() * arr.length)];

randomly([1, 3, 5, 7, 9, 11]);

//以字节为单位返回字符串的长度

const byteSize = str => new Blob([str]).size;

byteSize(\'Hello World\'); // 11

//获取不带任何参数或片段标识符的当前url

const getBaseURL = url => url.replace(/[?#].*$/, \'\');

getBaseURL(\'https://xx.com/index?q=hello&key=word\');

// https://xx.com/index

//生成指定范围内的随机整数

const randomIntegerInRange = (min, max) =>

Math.floor(Math.random() * (max - min + 1)) + min;

randomIntegerInRange(1, 7); // 1 - 7

//获取url上的参数

const getURLParams = url =>

(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(

(a, v) => (

(a[v.slice(0, v.indexOf(\'=\'))] = v.slice(v.indexOf(\'=\') + 1)), a

),

{}

);

getURLParams(\'https://www.baidu.com?q=hello&key=world\');

// {q: \'hello\', key: \'world\'}

//验证是否为正确电子邮箱

function check_input(){

var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;

if(!reg.test($(\"#email\").val())){

layer.msg(\'电子邮箱格式不正确!\', {icon:2,time: 1000});

$(\"#email\").focus();

return false;

}

return true;

}

//判断是否微信

function isWeiXin() {

var ua = window.navigator.userAgent.toLowerCase();

if (ua.match(/MicroMessenger/i) == \'micromessenger\') {

return true;

} else {

return false;

}

}

//获取当前时间戳

function _NowTime(){

var this_time = Date.parse(new Date());

this_time = \'\'+this_time;

this_time = this_time.substring(0,10);

this_time = parseInt(this_time);

return this_time;

}

标签: 函数 字符串

提交需求或反馈

Demand feedback