Dylanthepiguy
Dylanthepiguy

Reputation: 1731

JS regex - checking phone number for non-numeric characters

In this code, i want to check for non-numeric characters

<!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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
</head>

<body>
    <script>
        function test(phone) {
            console.log("original", phone)
            var ph = phone + ""; //Copy
            //remove spaces using regex
            ph = ph.replace(/\n/g, ""); //\n line
            ph = ph.replace(/\s/g, ""); //\s space
            console.log("removed", ph);

            //Check for non-numeric chars
            if (ph.indexOf(/\D/g) !== -1) return 1;
            console.log("replace", ph.replace(/\D/g, ""))
            console.log("find", ph.indexOf(/\D/g))
            if (phone.length < 7) return false;
            return true;
        }

        console.log("result", test("hi\n345bla345"))
    </script>

</body>

</html>

the console says this

original hi
345bla345 test.html:12
removed hi345bla345 test.html:17
replace 345345 test.html:21
find -1 test.html:22
result true

Why does replacing it work, but when trying to find the indexOf non-numeric chars, it doesn't work?

Upvotes: 1

Views: 433

Answers (2)

Dylanthepiguy
Dylanthepiguy

Reputation: 1731

AHA!! I found out why. The string.indexOf function doesn't support regex, but if you do this:

var rx = /\D/g;
if (rx.test(ph) == true) return 1;

then it works.

Upvotes: 0

Marco Bonelli
Marco Bonelli

Reputation: 69346

That happens because the .indexOf method checks if there are elements EQUAL to its argument. So if you call .indexOf(/abc/) it will check if your string contains the regexp /abc/ at some index, which obviously is never true, because your string only contains characters.

If you want to find the index of the first number you'll have to use a for statement like this:

var s = "ab123cd",
    i;
for (i=0; i<s.length; i++) {
    if (/\D/.test(s[i])) break;
}

console.log(i) // 2

Upvotes: 1

Related Questions