JavaScript: check if string contains '.' (a full

This question already has an answer here:

  • How to check whether a string contains a substring in JavaScript? 49 answers

  • Why does that happen?

    The reason why _email.search("."); returns 0 every time is because String.prototype.search takes a regular expression as its input.

    . means match any character in regex. In other words, if your input has at least one character of anything, it will return 0.


    The Solution

    If you simply change it to _email.search(/./); , it will work exactly as you intended.

    Browser support: All known browsers

    If you don't care about browser support, you may also use _email.includes('.'); as mentioned by Cade Brown.

    See here for reference. Browser support: Only Chrome 41+ and Firefox 40+ (recent browsers)


    You can use: string.includes(".") This returns true or false

    If you want a 1 or -1 , simply use:

    (x.includes(".")) ? 1 : -1

    EDIT:

    After searching a bit more, I ran across: Browser support for array.include and alternatives and others.

    Use x.indexOf(".") > -1


    search interprets its parameter as a regular expression, so you need to escape the . with a (double) backslash as it will otherwise match any character:

    var contains_dot = _email.search(".");
    

    But because you don't need a regular expression, it would be simpler to use indexOf :

    var contains_dot = _email.indexOf(".");
    
    链接地址: http://www.djcxy.com/p/2064.html

    上一篇: CATransform3DRotate和UIImageView

    下一篇: JavaScript:检查字符串是否包含'。' (满满的