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

后端 未结 4 1995
萌比男神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: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.

提交回复
热议问题