Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression not working in IE8

I'm going to test inserted character if it is rtl or ltr and I used this code:

function checkRTL(s) {
    var ltrChars = 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-
    \u1FFF' + '\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF',
            rtlChars = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC',

            rtlDirCheck = new RegExp('^[^' + ltrChars + ']*[' + rtlChars + ']');

    return rtlDirCheck.test(s);
}
;
function checkSpecialChars(s) {
    var sChars = '0-9`~!@#$%^&*()_+\\-=\\|\\[\\]{};\'":,.<>/',
            checkChar = new RegExp('^[' + sChars + ']+');
    return checkChar.test(s);
}
var input = $('#password').on('keypress', keypress);

function keypress(e) {
    setTimeout(function () {
        var isRTL = checkRTL(String.fromCharCode(e.charCode));
        var isSpecial = checkSpecialChars(String.fromCharCode(e.charCode));

        var dir = isRTL ? 'RTL' : 'LTR';
        if(dir=='RTL'){
            document.getElementById("langDir").innerHTML="<img src='../img
        /signup_images/att.png'>Hello!";
       $("#langDir").css("display","block");
        }
        else
        {
            document.getElementById("langDir").innerHTML="";
         $("#langDir").css("display","none");
        }
    }, 100);
}

This Code is working perfectly in IE 9, 10, Chrome and Firefox. But It's not working in IE8 After some debugging I've found out that this line:

    rtlDirCheck = new RegExp('^[^' + ltrChars + ']*[' + rtlChars + ']');

    return rtlDirCheck.test(s);

always returns False. What is wrong with that?

like image 732
Super Hornet Avatar asked Mar 25 '26 04:03

Super Hornet


1 Answers

First of all I can detect nothing wrong with your regex. Also with the following html IE 7 to 10 always tells me the result equals true (I am using IE 10.0 in backwards compatibility modes).

<html>
<body>
<script>
var ltrChars = 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF' + '\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF',    
rtlChars = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC',
rtlDirCheck = new RegExp('^[^' + ltrChars + ']*[' + rtlChars + ']');

alert("result = "+ rtlDirCheck.test('\u0591') );
</script>
</body>
</html>

The problem is thus not this function. It most likely is its input:

String.fromCharCode(e.charCode)

IE doesn't set e.charCode, but used e.keyCode. Actually e.charCode is only used by webkit browsers. Have a look at chapter 3 of this excellent breakdown of all the differences between keyboard events in different browser. I would suggest using:

String.fromCharCode(e.which || e.keyCode)
like image 79
Lodewijk Bogaards Avatar answered Mar 26 '26 18:03

Lodewijk Bogaards



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!