How to split a String by last delimiter in ColdFusion

Viewed 1250

In CF9, I have a string like C:\Docs\472837\nyspflsys\Medical Report\XLSX_46.xlsx

I want to split it by last backward slash, so it should look like
array[1] = C:\Docs\472837\nyspflsys\Medical Report and
array[2] = XLSX_46.xlsx

How to do it in ColdFusion 9 ?

4 Answers

You may want to consider using GetDirectoryFromPath and GetFileFromPath.

<cfset fullPath = "C:\Docs\472837\nyspflsys\Medical Report\XLSX_46.xlsx">

<cfset dirPath  = getDirectoryFromPath(fullPath)>    <!--- C:\Docs\472837\nyspflsys\Medical Report\ --->
<cfset dirPath  = reReplace(dirPath, "[\\/]$", "")>  <!--- C:\Docs\472837\nyspflsys\Medical Report  --->
<cfset fileName = getFileFromPath(fullPath)>         <!--- XLSX_46.xlsx                             --->
<cfset myString = "C:\Docs\472837\nyspflsys\Medical Report\XLSX_46.xlsx" />
<cfset myArray = ArrayNew(1) /> 
<cfset myArray[2] = ListLast(myString, "\") />
<cfset myArray[1] = REReplace(myString, "\\" & myArray[2] & "$", "") />


<cfdump var="#myArray#" />

I always use reverse and listRest in this situation because it makes sense conceptually to me.

<cfset test = "C:\Docs\472837\nyspflsys\Medical Report\XLSX_46.xlsx" />
<cfset arr = [
    reverse(listRest(reverse(test), "\")),
    listLast(test, "\")
] />
<cfdump var="#arr#" />

https://trycf.com/gist/71a788189d26944c0fa461f255ab6cc2

Could instead use listDeleteAt(test, listLen(test, "\"), "\") but that just doesn't feel as clean to me. Either work well enough though

I agree with Alex about the built in functions, but if you still want to parse it yourself then this way is much more efficient than the other answers so far (example shown in cfscript syntax):

path = "C:\Docs\472837\nyspflsys\Medical Report\XLSX_46.xlsx";

file = listLast(path, "/\");               // account for unix path separator as well
dir  = left(path, len(path) - len(file));

If you are using Lucee, then you can take advantage of the negative length input for left(), like so:

dir = left(path, -len(file));             // Lucee only, passing negative length to left()

Bear in mind that this method keeps the trailing path separator in dir, so if you want to remove it you need to remove one more character, i.e. - len(file) - 1

Related