Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery check if string starts with 1234

Tags:

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!

like image 876
Dragan Avatar asked Nov 10 '11 00:11

Dragan


People also ask

How do you check if a string starts with in jquery?

startsWith() and endsWith() method: It checks whether a string starts or ends with the specific substring.

How to check if a string starts with a Number in JavaScript?

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.

How to check if the string starts with a Number RegEX?

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!

How do you check a string starts with and ends with?

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.


1 Answers

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"; 
like image 56
gilly3 Avatar answered Sep 18 '22 13:09

gilly3