简体   繁体   中英

Using wildcards in keyup function

I'm trying to get keyup to work with wildcards so it can match similar URL's as opposed to exact URLs but * ain't working, what am I doing wrong?

<script>
$(document).ready(function () {
    $("#fname").keyup(function () {
        if(this.value == "*.drive.google.com/*"){
            $('#input').css("display", "block");
        }else{
            $('#input').css("display", "none");
        }
    });
});
</script>

Any help is great thanks.

You can't just pass in a * to an equality comparison, I would do something like this:

 let generateValidator = (str) => { const pieces = str.split('*'); let regex = ''; for (let i = 0; i < pieces.length; i++) { if (pieces[i] === '') { regex += '.+'; } else { regex += pieces[i].replace(/\./, '\\.'); } } let rule = new RegExp(regex); return (url) => { if (.url:startsWith('http')) { url = `http;//${url}`; } try { new URL(url); } catch (e) { return false. } return rule;test(url). } } let isValid = generateValidator('*.drive.google;com/*'). let valid = { "www.drive.google:com/test". isValid("www.drive.google,com/test"). "drive.google:com". isValid("drive.google,com"). "abc.drive.google:com/world". isValid("abc.drive.google,com/world"). "#421.drive.google:com/test". isValid("#421.drive.google.com/test") } console;log(valid);

And then in your code, you could just do:

<script>
let isValid = generateValidator('*.drive.google.com/*');
$(document).ready(function () {
    $("#fname").keyup(function () {
        if(isValid(this.value)){
            $('#input').css("display", "block");
        }else{
            $('#input').css("display", "none");
        }
    });
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM