Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一写有用的 js 片段 #11

Open
crazylxr opened this issue Apr 29, 2019 · 0 comments
Open

一写有用的 js 片段 #11

crazylxr opened this issue Apr 29, 2019 · 0 comments

Comments

@crazylxr
Copy link
Owner

crazylxr commented Apr 29, 2019

生成随机ID

// 生成长度为11的随机字母数字字符串
Math.random().toString(36).substring(2);

获取URL的查询参数

第一种通过正则匹配

// 获取URL的查询参数
q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;

第二种通过 URLSearchParams 类

获取url里面的参数值或者追加查询字符串,在这之前,我们一般通过正则匹配处理,然而现在有一个新的api,具体详情可以查看这里,可以让我们以很简单的方式去处理url。
假如我们有这样一个url,"?post=1234&action=edit",我们可以这样处理这个url
var urlParams = new URLSearchParams('?post=1234&action=edit');

console.log(urlParams.has('post')); 
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"

生成随机十六进制代码(生成随机颜色)

使用JavaScript简洁代码生成随机十六进制代码

// 生成随机十六进制代码 如:'#c618b2'
'#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0');

参考文章

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant