小技巧!前端JS实现过滤指定内容~

1、JS实现验证码倒计时

/*点击获取验证码*/
$(".addCode").click(function(event) {
    var addCode = $(".addCode")
    verificationCode(addCode);
});
/*验证码的方法*/
function verificationCode(name) {
    var num = 20;
    var timer = setInterval(function() {
        num--;
        name.attr("disabled", "disabled").html(num + '秒后重试');
        if (num == 0) {
            clearInterval(timer);
            name.attr("disabled", false).html("重新获取");
        }
    }, 1000)
}

2、CSS实现文字分散对齐

注意:只支持高版本Chrome浏览器

text-align-last:justify;
text-align:justify;
text-justify:distribute-all-lines;

3、JS过滤指定内容

function replaceText(words) {

    let text = '你是个傻逼,我才不想你这个傻逼呢。大傻逼!'
    for (var i = 0; i < words.length; i++) {
        document.body.innerHTML = text.replace(new RegExp(words[i], 'ig'), '**');
    };
}

const words = ['傻逼']; // 敏感词
replaceText(words)

// 你是个**,我才不想你这个**呢。大**!

4、Div跟随另外一个Div高度自适应

// 最外层设置CSS

display: flex;
align-items: center;
flex-direction: column;

5、JS随机从数组中取指定值

let groups = ['1','2','4','5','6','7','8','9','10'];

1.从数组groups中随机取出一个值

let value = groups[Math.floor(Math.random()*groups.length)];

value  // 10

2.随机从数组中随机取几个值

getRandomArrayValue(arr, num) {
    var sData = arr.slice(0), i = arr.length, min = i - num, item, index;
    while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        item = sData[index];
        sData[index] = sData[i];
        sData[i] = item;
    }
    return sData.slice(min);
}

getRandomArrayValue(groups, 4)

// ["7", "8", "10", "2"]