28

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.

haveman
  • 311
  • 1
  • 3
  • 13

4 Answers4

47

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 */
}
Arnab_Datta
  • 602
  • 7
  • 8
  • Can you please explain why we need that 'g' at the end of the regular expression? – Asmat Ali Dec 17 '20 at 12:01
  • 1
    @AsmatAli `/g` not needed as we're only interested if there is at least 1 letter in the string – ellockie Mar 23 '21 at 01:25
  • 1
    I guess this will work only for latin characters? – emvaized May 17 '21 at 01:20
  • 2
    CAUTION, make sure to remove the "g"! The addition of the "g" causes the regex to sometimes fail. Try copying the exact code in this answer and putting it inside a for loop that runs 100 times. Out of the 100 times, it fails 20 times saying no letters were found. The amount of times it fails seems to depend on the input text being tested. I have no idea why it's like this. – train Mar 19 '22 at 00:35
  • 2
    this will work only for alphabet characters and will not work if you have symbols like € or $ – De Bonheur Mar 25 '22 at 03:11
12
/[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.

ellockie
  • 3,730
  • 6
  • 42
  • 44
5

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
brc-dd
  • 10,788
  • 3
  • 47
  • 67
-1

you can do this:

 export function containsCaracter(value) {
      return isNaN( +value / 1) || 
          value.includes('+') || value.includes('-') ;
    }
De Bonheur
  • 742
  • 10
  • 13