Regular expression for only characters a-z, A-Z

后端 未结 4 1987
萌比男神i
萌比男神i 2020-12-02 22:57

I don\'t know how to create a regular expression in JavaScript or jQuery.

I want to create a regular expression that will check if a string contains only characters

相关标签:
4条回答
  • 2020-12-02 23:28
    /^[a-zA-Z]+$/ 
    

    Off the top of my head.

    Edit:

    Or if you don't like the weird looking literal syntax you can do it like this

    new RegExp("^[a-zA-Z]+$");
    
    0 讨论(0)
  • 2020-12-02 23:29

    With POSIX Bracket Expressions (not supported by Javascript) it can be done this way:

    /[:alpha:]+/
    

    Any alpha character A to Z or a to z.

    or

    /^[[:alpha:]]+$/s
    

    to match strictly with spaces.

    0 讨论(0)
  • 2020-12-02 23:49
    /^[a-zA-Z]*$/
    

    Change the * to + if you don't want to allow empty matches.

    References:

    Character classes ([...]), Anchors (^ and $), Repetition (+, *)

    The / are just delimiters, it denotes the start and the end of the regex. One use of this is now you can use modifiers on it.

    0 讨论(0)
  • 2020-12-02 23:50

    Piggybacking on what the other answers say, since you don't know how to do them at all, here's an example of how you might do it in JavaScript:

    var charactersOnly = "This contains only characters";
    var nonCharacters = "This has _@#*($()*@#$(*@%^_(#@!$ non-characters";
    
    if (charactersOnly.search(/[^a-zA-Z]+/) === -1) {
      alert("Only characters");
    }
    
    if (nonCharacters.search(/[^a-zA-Z]+/)) {
      alert("There are non characters.");
    }
    

    The / starting and ending the regular expression signify that it's a regular expression. The search function takes both strings and regexes, so the / are necessary to specify a regex.

    From the MDN Docs, the function returns -1 if there is no match.

    Also note: that this works for only a-z, A-Z. If there are spaces, it will fail.

    0 讨论(0)
提交回复
热议问题