Reputation: 9
I have a regular expression in javascript as follows:
var regex = /(\d{2,3})(\D{1,2})(\d{1,8})/;
that should display the first part in 2 or 3 digits, then 1 to 2 non-digit characters, then 1 to 8 digits
to form something that looks like this: 45ER12345
My question is how do I turn this into an array with variables (a long one without the complex (\d{2.3}) stuff that would benefit a beginner coder.)
var regex = /(\d{2,3})(\D{1,2})(\d{1,8})/;
var stringBits = regex.exec(form.cname.value);
//This ties the variables to the text below that will appear in an alert box
alert("Hello " + form.fname.value + ". Your car's year is " + stringBits[1] + " and your county is " + stringBits[2] + " the car number is " + stringBits[3] );
return true; // Form is good / processing successfully complete
}
This is what I have written. Not seen in this is the 2 input boxes where the user puts in their name and car reg. the result should parse the car reg like shown in the first example and displays it in a box.
The regular expression I have been using does exactly what I want it to do but I just want to turn it into a simpler array without all the complex notations that a beginner would not use.
Upvotes: 1
Views: 68
Reputation: 784998
Your regex seems to be fine you're just looking for String#match(regex)
:
var regex = /(\d{2,3})(\D{1,2})(\d{1,8})/;
var s = '45ER12345';
var m = s.match(regex);
//=> ["45ER12345", "45", "ER", "12345"]
Upvotes: 1