'Javascript Validate only .com websites how to validate?

For Example:-

google.com msn.com

other than .com is not allowed how to wrote the regex?



Solution 1:[1]

If you only need to ensure that the string ends with ".com" this regex should work :

^.*\.com$

Solution 2:[2]

This is what foundation abide library states regex for validating a domain:

/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$/

just modified it to only accept .com:

/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+com$/

Solution 3:[3]

var site_path=window.location.origin;
var splitted_path=site_path.split(".");
if(splitted_path[splitted_path.length-1]=="com")
{
    // DO IF .COM.
}
else
{
    // DO IF ANOTHER.
}

Solution 4:[4]

Just split them when . comes and check if the current element is equals to .com for every element Your question answer is the below code:

const validateCom = (str) =>{
    let total = ""
    let errorMessage = ""
    let error = false;
    if(str != null && str != ""){
        let array = str.split(".")
        array.forEach((element=>{
            if(element === "com"){
                total = "Yes, its .com"
                // Type your code if its .com here
            }else{
                total = "No, its not .com"
                // Type your code if its not .com here
            }
        }))
    }else{
        error = true;
        errorMessage = "Please fill the str perimeter"
        return errorMessage
    }
    return total;
}

// Calling Function
console.log(validateCom("demo.com"));

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 Ki Jéy
Solution 2 Akshay Shinde
Solution 3 mor jaydeep
Solution 4 Evil-Coder