Skip to main content
WolfShade
Legend
March 4, 2020
Question

Just wanted to share something with you all.. a RegEx replace for a specific CF tag..

  • March 4, 2020
  • 2 replies
  • 906 views

Hello, all,

 

For the last several months, I've been working on code that was written many, many moons ago by someone who left for greener fields back in 2013 or 2014.  It is chock full of one of my pet-peeves: isDefined().

 

So, I'm cringing everytime I look at this code with isDefined() all over the place.  After several months, I've decided:  Every current CF dev at my work knows StructKeyExists() and even (like me) prefers it.  I finally decided to do something about it, and I'm sharing it for anyone who is interested.

 

We use Dw, here, but this will work in any IDE that has a RegEx Find/Replace.

 

 

// Find and replace isDefined("{scope}. with StructKeyExists({scope}," 
FIND:     isdefined\(\s*(['"])\s*(url|variables|server|cgi)\.
REPLACE:  StructKeyExists($2,$1

 

Of course, feel free to add scopes, I just used the four for brevity.  I hope someone finds this useful.

 

V/r,

 

^ _ ^

This topic has been closed for replies.

2 replies

WolfShade
WolfShadeAuthor
Legend
March 5, 2020

Hi, Jamo,

 

You don't have to do a StructKeyExists for each level.  Place the one StructKeyExists inside a CFTRY/CFCATCH and process the error as you best see fit (case-by-case).

 

As far as using anything that contains evaluate, I'd rather not.. ever.  I don't even use eval in JavaScript.  I adhere to the "eval is evil" mentality.  🙂

 

V/r,

 

^ _ ^

James Moberg
Inspiring
March 4, 2020

You may want to extend the regex to support more types of scopes (ie, form, request, cookie, session, etc.)  Variables that don't have a scope are in the "variables" scopes (which should be avoided).  [Sorry.  I just saw you mentioned you only included four (4) for brevity.]

I ocassionally use isDefined() to determine if a sub-key of a struct exists ex, isDefined("Request.CSPRules.iFrame") as it's more convenient than performing multiple StructKeyExists function calls to determine if "CSPRules" is present and then "iFrame" is present.

Server-wise, I've been using this UDF since 2017 to determine if an element exists and has "length".  (DISCLAIMER: It's kinda dangerous as it uses "evaluate", but it's necessary if you don't know exactly what type of value is being passed to the function.)

https://gist.github.com/JamoCA/e9fd556c3f7c01c5c4a23c44555ba411