skip to Main Content

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.

4

Answers


  1. 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 */
    }
    Login or Signup to reply.
  2. /[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.

    Login or Signup to reply.
  3. If one wants to add support for non-ASCII letters also, then they may use Unicode property escapes.

    const str_1 = '大阪';
    const str_2 = '123';
    
    console.log(/p{L}/u.test(str_1)); // true
    console.log(/p{L}/u.test(str_2)); // false
    Login or Signup to reply.
  4. you can do this:

     export function containsCaracter(value) {
          return isNaN( +value / 1) || 
              value.includes('+') || value.includes('-') ;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search