'Regex issue with JavaScript

Just like the title I have an issue with the following code

function checkPhone(phone){
    var reg = "/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im";
    var result=phone.match(reg);
    if (result) {
        console.log("(true)phone  "+phone);
        return (true)
    } else {
        console.log("(error)phone "+phone);

    }
}
<div class="form-group">
                <label >Numero di Telefono</label><br>
                <input type="text" id="phone" onchange="checkPhone(this.value)" placeholder="Insert phone number">
</div> 

Regardless of what I try to put in phone, it will result in "(error)phone "+phone. I have also tried it online and it works.

How can I fix the issue?



Solution 1:[1]

The problem is that you have quotes around the regular expression. Try this:

function checkPhone(phone){
    var reg = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;
    var result=phone.match(reg);
    if (result) {
        console.log("(true)phone  "+phone);
        return (true)
    } else {
        console.log("(error)phone "+phone);

    }
}
<div class="form-group">
                <label >Numero di Telefono</label><br>
                <input type="text" id="phone" onchange="checkPhone(this.value)" placeholder="Insert phone number">
</div>

See Regular Expressions on MDN.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ztcollazo