Ukuser32
Ukuser32

Reputation: 2189

Javascript regex not matching - full code included

I posted this query earlier and got the included response but I cannot seem to make this query match - I'm using Firefox. What on earth am I missing? (should be copy/pastable)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
    </head>
    <body>
            <script type="text/javascript">
                    $('#inp1').on('keyup',function(){
                            $('#out1').val($(this).val().match(/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*([^\w]|_)).{8,}/));
                    })
            </script>
            Inp <input id="inp1" type="text" value="fDe^je872Fhdj"><br>
            Out <input id="out1" />        
    </body>
    </html>

Upvotes: 1

Views: 54

Answers (1)

Amit Joki
Amit Joki

Reputation: 59272

match() returns Array. Use the index to grab the first and only value, which is the whole match.

$(this).val().match(/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*([^\w]|_)).{8,}/)[0]);
                                          // index      <-----------------^

And use your code inside DOM ready, since the elements are not yet present at that point.

$(document).ready(function() {
    $('#inp1').on('keyup', function() {
        $('#out1').val($(this).val().match(/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*([^\w]|_)).{8,}/)[0]);
    })
});

Upvotes: 2

Related Questions