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.
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.
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.
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!
The includes() method returns true if a string contains a specified string. Otherwise it returns false .
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 */
}
/[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With