Split string at length

Explorer ,
Nov 06, 2019 Nov 06, 2019

Copy link to clipboard

Copied

I'm working on creating a data conversion extract and need to split a string into multiple lines, 132 chars each.  At this time, they don't want to break at the last space before the 132 chars, they just want to continue it on the next line.  I'm fairly new to coldfusion and am not sure how to do this.  Suggestions, please?

Thank you.

 

-=Rob=-

TOPICS
Advanced techniques

Views

104

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Nov 06, 2019 Nov 06, 2019

Copy link to clipboard

Copied

LATEST

Not sure I fully comprehend your request.  Are you saying that if you have a string that is, arbitrarily, 500 characters in length, you want to break it down to 132 character increments, but for some reason ...

 

NM.. think I understand, now.  I'm assuming, of course, that the string is not like a non-space sequence, but rather like a paragraph.

 

Yes, it can be done, but you have to reverse the string to do it.  I found this function a while ago, probably on CFLIB, that will truncate a string at nn characters, but will take spaces into consideration and place an ellipse after the space that occurs just before the limit.  You will have to play around with it to get precisely what you want, but here it is.

 

 

 

<cfscript>
    function abbrev(required string str, required numeric leng){
        var newString = REReplace(str,"<[^>]*>"," ","all"); // Removes HTML; not necessary
        var lastSpace = 0;
        newString = REreplace(newString," \s*"," ","all"); // Replaces multiple spaces with one
        if(len(newString) gt leng){
            newString = left(newString, leng);
            lastSpace = find(" ",reverse(newString));
            lastSpace = len(newString) - lastSpace;
            newString = left(newString), lastSpace);
            }        
        }
</cfscript>

 

 

You use it like <cfset modString = abbrev(originalString,132) />, so modString will be the first character of originalString through to the last space just before or at 132nd character of the originalString.  This will get you the first 132.  If there are more after that, then you could make a copy of the original string, and loop it until there's nothing left, setting a new modString variable to equal the output.

 

Just my two cents.

 

HTH,

 

^ _ ^

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines