Home > Mobile >  ColdFusion - Taking a string and breaking it down into individual variables
ColdFusion - Taking a string and breaking it down into individual variables

Time:08-12

I am receiving a string from another application that contains various pieces of information. The items are always in the same order, but the length of variable information can change. Each item is separated by an underscore and prefixed by a letter and colon.

Example:

A:12345678_B:5482945_C:20220911_D:20230402_E:3.94

Ideally, I want to break it down so that (in Coldfusion) I can end up with a series of variable that I would set as the values of A,B,C,D and E above.

Does anyone know any easy way to do this?

Thanks!

CodePudding user response:

Gives you an array of the items. If you're handy with Regular Expressions, this could be even simpler. This is Lucee compatible. Adobe CFML didn't like the var commands outside of a function.

<cfscript>
 var aNewItems = [];
 var sString = "A:12345678_B:5482945_C:20220911_D:20230402_E:3.94";
 var aItems = listToArray(sString, "_");
 for( var sLetter in aItems){
    aNewItems.append(listFirst(sLetter, ":"));
 }
 writeDump(aNewItems);
</cfscript>

Here's an Adobe CFML version that worked on TryCF.com:

<cfscript>
 local.aNewItems = [];
 local.sString = "A:12345678_B:5482945_C:20220911_D:20230402_E:3.94";
 local.aItems = listToArray(local.sString, "_");
 for( local.sLetter in aItems){
    local.aNewItems.append(listFirst(local.sLetter, ":"));
 }
 writeDump(local.aNewItems);
</cfscript>

CodePudding user response:

I think @Will is missing one small part of your requirement, which is

I can end up with a series of variable[s] that I would set as the values of A,B,C,D and E above"

To me this demonstrates more what you want to achieve:

raw = "A:12345678_B:5482945_C:20220911_D:20230402_E:3.94"

asArray = raw.listToArray("_")
asStruct = asArray.reduce((struct, kvAsString) => {
    var key = kvAsString.listFirst(":")
    var value = kvAsString.listRest(":")
    struct[key] = value
    return struct
}, {})

writeDump(asStruct)

(runnable @ trycf.com: dump showing results of code

Whilst this does not create "a series of variables" it does separate out the key from the value, and from there you can append that to whatever scope you need the variables in (eg: variables.append(asStruct))


In future please:

  1. show us what you've already tried
  2. give us the full intended result, don't just describe it.

Basically: always include code when you ask questions.

  • Related