Thanks for taking the time to answer my question.
I want to check if a string has exactly 7 characters and starts with "1234". How do I do that?
I know of string.substring but am not sure if I shouold use regex or are there any other alternative. Thanks in advance!
startsWith() and endsWith() method: It checks whether a string starts or ends with the specific substring.
The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false . The startsWith() method is case sensitive. See also the endsWith() method.
To check if a string ends with a number, call the test() method on the following regular expression - /^\d/ . The test method will return true if the string starts with a number, otherwise false will be returned. Copied!
Example 1: Check String Using Built-in MethodsThe startsWith() method checks if the string starts with the particular string. The endsWith() method checks if the string ends with the particular string.
Simple RegExp:
var isMatch = /^1234...$/.test(myString);
Or:
var isMatch = myString.length == 7 && myString.indexOf("1234") == 0;
Edit: Or:
var isMatch = myString.length == 7 && myString.substr(0, 4) == "1234";
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