Created
April 15, 2013 15:02
-
-
Save si/5388750 to your computer and use it in GitHub Desktop.
Find elements in CakePHP form field naming convention
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is the naming convention for date fields | |
var field_name = "data[model][0][dob][day]"; | |
// Existing regular expression for finding elements. | |
var reg_fields = /^data\[([a-zA-Z]+)\]\[(\d+)\]\[([a-zA-Z]+)\]\[([a-zA-Z]+)\]?$/ ; | |
// Match on date fields works ok (not sure why the first index is the full string). | |
field_elements = field_name.match(reg_fields); | |
// returns [ "data[model][0][dob][day]" , "model" ,"0", "dob", "day" ] | |
// This is the naming convention for text fields | |
field_name = "data[model][0][first_name]"; | |
// Match on text fields doesn't work. | |
field_elements = field_name.match(reg_fields); | |
// returns null |
To answer your confusion (on line 7): when doing a match
, it returns the entire portion in the string that matches the regex as the first item in the array.
Perhaps this would be a better approach:
var tmp = field_name.replace(/^data\[(.*)\]$/, '$1'); // "model][0][first_name"
field_elements = tmp.split(']['); // ["model", "0", "first_name"]
Hope that helps.
@SteveMarshall, those extra brackets around the final rule work a charm.
@remybach, that's not such a bad idea. That way, I've got a "clean" array of just the elements I'm after rather than the extra matches (now including the [day]
, [month]
and [year]
matches before day
, month
and year
matches respectively).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your regex isn’t quite saying what you think. It’s saying
data[:letters:][:numbers:][:letters][:letters:
ordata[:letters:][:numbers:][:letters][:letters:]
are the only valid matches†. You should change\[([a-zA-Z]+)\]?$
to(\[([a-zA-Z]+)\])?$/
, if that’s not what you want.† obviously using
:letters:
and:numbers:
as proxies for([a-zA-Z]+)
and(\d+)
, respectively.