Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains any letter (Javascript/jquery)

How can i check if a string contains any letter in javascript?

Im currently using this to check if string contains any numbers:

    jQuery(function($){
    $('body').on('blur change', '#billing_first_name', function(){
    var wrapper = $(this).closest('.form-row');
    // you do not have to removeClass() because Woo do it in checkout.js
    if( /\d/.test( $(this).val() ) ) { // check if contains numbers
    wrapper.addClass('woocommerce-invalid'); // error
    } else {
    wrapper.addClass('woocommerce-validated'); // success
    }
    });
    });

However i want it to see if it contains any letters.

like image 818
zal ador Avatar asked May 01 '20 20:05

zal ador


People also ask

How do you check if a string contains any letters in JavaScript?

To check if a string contains any letter, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise.

How do I check if a string contains certain letters?

Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.

How do you check if a string contains a letter and a number in JavaScript?

Use the test() method on the following regular expression to check if a string contains only letters and numbers - /^[A-Za-z0-9]*$/ . The test method will return true if the regular expression is matched in the string and false otherwise. Copied!

How do you check if a string contains a word in JavaScript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .


2 Answers

You have to use Regular Expression to check that :-

var regExp = /[a-zA-Z]/g;
var testString = "john";
            
if(regExp.test(testString)){
  /* do something if letters are found in your string */
} else {
  /* do something if letters are not found in your string */
}
like image 97
Arnab_Datta Avatar answered Oct 09 '22 04:10

Arnab_Datta


/[a-z]/i.test(str)

Returns:

  • true - if at least one letter is found (of any case, thanks to the /i flag)
  • false - otherwise

/i - case insensitive flag

(/g - global flag (allows multiple matches) - in this scenario it would be at least redundant, if not harmful for the performance. Besides it sets the lastIndex property of regex (would be of concern if regex was used as a constant / variable and multiple tests were performed))

Note:

/[a-z0-9]/i.test(str)

would match any alphanumerical.

like image 42
ellockie Avatar answered Oct 09 '22 02:10

ellockie