javascript 如何在javascript中的任何一点检查字符串是否包含字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27820724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:02:28  来源:igfitidea点击:

How to check if string contains character at any point in javascript

javascriptregexstring

提问by Furious Gamer

I need to know if a string contains a character (one or multiple times) at any point of the string. For example with the character "&":

我需要知道一个字符串是否在字符串的任何一点包含一个字符(一次或多次)。例如使用字符“&”:

"&hfds" is invalid, "%$/&h&" is invalid etc.

“&hfds”无效,“%$/&h&”无效等。

Im doing this as part of a password validation:

我这样做是作为密码验证的一部分:

function applySpecialCharacterFilter(password) {
    if (password.match(/([!,%,@,#,$,^,*,?,_,~])/)) {
        return 1;
    } else if(password.match(/([&])/)) {
        throw new Error('Das Passwort enth?lt unerlaubte Zeichen.');
    }
    return 0;
}

in the first part it checks of the password contains any of the allowed characters, and then increments the value of the validation. But then passwords containing not allowed characters can pass. With the else if im trying to catch it, but it only works if its not in a special character sequence like $%&

在第一部分,它检查密码是否包含任何允许的字符,然后增加验证的值。但是包含不允许字符的密码可以通过。使用 else if im 试图捕捉它,但它仅在它不在像 $%& 这样的特殊字符序列中时才有效

Thank you

谢谢

Edit:

编辑:

Here is the whole function:

这是整个功能:

function checkStrength(password){
        var strength = 0;
        var passwordMessage = $('#passwordMessage');

        if (password.length == 0) {
            result.removeClass();
            return '';
        }

        if (password.length < 6) {
            validPassword = false;
            result.removeClass();
            result.addClass('short');
            return 'Too short';
        } else if(password.length > 8) {
            validPassword = false;
            result.removeClass();
            result.addClass('short');
            return 'Too long';
        } else {
            strength += 1;
        }

        try {
            strength += applyLowerAndUpperCaseFilter(password);
            strength += applyNumbersAndCharactersFilter(password);
            strength += applySpecialCharacterFilter(password);
            strength += applyTwoSpecialCharacterFilter(password);
            strength += applyAlphabeticalCharacterCriteria(password);
        } catch(error) {
            validPassword = false;
            result.removeClass();
            result.addClass('short');
            passwordMessage.html('').append('<p>TPassword contains invalid characters!</p>');
            return 'Invalid';
        }

        passwordMessage.html('');

        if (strength <= 2) {
            validPassword = false;
            result.removeClass();
            result.addClass('weak');
            return 'Schwach';
        } else if (strength <= 3 ) {
            validPassword = true;
            result.removeClass();
            result.addClass('good');
            return 'Good';
        } else {
            validPassword = true;
            result.removeClass();
            result.addClass('strong');
            return 'Strong';
        }
    }

    function applyLowerAndUpperCaseFilter(password) {
        if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))
            return 1;
        return 0;
    }

    function applyNumbersAndCharactersFilter(password) {
        if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))
            return 1;
        return 0;
    }

    function applySpecialCharacterFilter(password) {
        if (password.match(/^([!%@#$^*?_~]+)$/)) {
            return 1;
        } else if(password.match(/([&])/)) {
            throw new Error('Das Passwort enth?lt unerlaubte Zeichen.');
        }
        return 0;
    }

    function applyTwoSpecialCharacterFilter(password) {
        if (password.match(/(.*[!,%,@,#,$,^,*,?,_,~].*[!,",%,@,#,$,^,*,?,_,~])/))
            return 1;
        else if(password.match(/([&])/))
            throw new Error('Das Passwort enth?lt unerlaubte Zeichen.');
        return 0;
    }

    function applyAlphabeticalCharacterCriteria(password) {
        var quality = 0;
        var sequences = [
            'abcdefghijklmnopqrstuvwxyz',
            '01234567890',
            '!\"§$%/()=?'
        ];

        var proceed = true;
        for(var i=0; i<(password.length-3); i++) {
            for(var index = 0; index < sequences.length; index++) {
                var needle = password.substring(i, 3);
                if(stripos(sequences[index], needle) != false) {
                    quality -= 1;
                    proceed = false;
                }
                if(proceed == false) break;
            }
            if(proceed == false) break;
        }
        return quality;
    }

    function stripos(f_haystack, f_needle, f_offset) {
        var haystack = (f_haystack + '')
            .toLowerCase();
        var needle = (f_needle + '')
            .toLowerCase();
        var index = 0;

        if ((index = haystack.indexOf(needle, f_offset)) !== -1) {
            return index;
        }
        return false;
    }

The messages and classes are for real time validation output only. Rules: The Password needs to be between 6 and 8 characters long.
It has to have at least 1 upper and 1 lower case character.
It has to have numbers.
It has to have at leats 1 special characters (2 give more value).
Only these special characters are allowed - _ . : , ; ! @ § $ % / = ? #
The characters should not appear in a sequence if possible, so no abc,123,!§$ etc.

消息和类仅用于实时验证输出。规则:密码长度必须在 6 到 8 个字符之间。
它必须至少有 1 个大写和 1 个小写字符。
它必须有数字。
它必须至少有 1 个特殊字符(2 个赋予更多价值)。
只允许使用这些特殊字符 - _ 。: , ; !@ § $ % / = ? #
如果可能,字符不应该出现在一个序列中,所以没有 abc,123,!§$ 等。

回答by Toto

You have to anchor the first regex and add a quantifier:

您必须锚定第一个正则表达式并添加一个量词:

if (password.match(/^([!,%,@,#,$,^,*,?,_,~]+)$/)) {
//             here ^                      ^ ^

The comma is not mandatory except if you want to match it:

逗号不是强制性的,除非您想匹配它:

if (password.match(/^([!%@#$^*?_~]+)$/)) {

回答by giammin

You can use indexOfmethod:

您可以使用indexOf方法:

function applySpecialCharacterFilter(password) {
    if (password.indexOf('&')>-1) {
        throw new Error('Das Passwort enth?lt unerlaubte Zeichen.');
    }
    if (password.match(/^([!,%,@,#,$,^,*,?,_,~]+)$/)) {
        return 1;
    }
    return 0;
}

and you need to change your Regexp according @M42 answer

并且您需要根据@M42 答案更改您的正则表达式