2

How can I check the length of in String in JavaScript? Here is a small code example:

if(value != null && value != "" && value.length !== 10 && !value.match(/^\d*$/)){

   // do something

}

The expression 'value.length !== 10' doesn´t work. A String must contain at least 10 characters. How can I solve this problem?

2
  • 2
    "at least 10" means value.length >= 10. You are checking for exactly 10 and besides your check is !== "not equal value or not equal type" which in your case is useless. Commented Oct 22, 2015 at 6:58
  • value.trim().length >= 10 Commented Mar 18, 2019 at 16:27

3 Answers 3

7

Instead of match, test can be used with proper regex \d{10,}.

if (value && /^\d{10,}$/.test(value.trim()))
Sign up to request clarification or add additional context in comments.

2 Comments

And if I need exactly 10 characters? What is the correct expression?
@Marwief \d{10} the , after 10 says that at least 10 characters(digits here), you can remove , to match exact 10 characters
4

To Get the string length of a value for example:

var value="This is a string";
var string_length=value.length;
/*The string length will result to 16*/

Hope this helps

Comments

0
var regex = new RegExp(/^\d*$/),
    value = $.trim("1234567890");

if (value.length >= 10 && regex.exec(value)) {
   // correct
} else {
   // incorrect
}

1 Comment

Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.