[Tip] Elegant RegExp.exec() example
I just figured out that the RegExp.exec() function cycles through all matches when used with the "g" flag on (because it starts searching from the end position from the last time it was run). Starting with:
[image unavailable: Picture 17]
The amount of code needed to return all editable area names in a Sutra CMS template file is reduced to:
var fileData = plugins.file.readTXTFile( result )
if (fileData) {
// find and store editable regions
var regexp = /pageData\.get\(\"([A-Z0-9 _]*)\"/gi // match: <%=pageData.get("Sidebar")%>, any combination of letters, numbers, spaces and undersores
var occurrence = null;
var editables = []
while (occurrence = regexp.exec( fileData )){
editables.push(occurrence[1])
}
Each iteration through changes the RegExp object which returns other useful info:
[image unavailable: Picture 15]
Waded through a bazillion google search results before this one tipped me off (google as a search engine is starting to piss me off—talk about SEO spam):
http://www.bennadel.com/blog/697-Javascript-Exec-Method-For-Regular-Expression-Matching.htm
Pretty sweet. After years, finally figured this regexp technique out. I'm almost to the point where I may never have to use a Utils.string..() function ever again. Yay, better late than never.
Comments (2)