Search code examples
coldfusioncoldfusion-9cfml

How to replace the first two digits with one digit Coldfusion


I'd like to replace the first two digit and replace it with 0 In case it start with 0 then nothing need to be changed. Example: 445656 to 056....

<cfif number (BEGIN WITH?) "44">
<cfset number = Right(number , Len(number )-2) /> 

But this just will remove the first two digits. thank you for the support


Solution

  • It looks like you're keeping your numbers that "start with 0" as strings. Try this:

    <!--- // a number that does not start with zero --->
    <cfset theNumber = "445656" />
    <cfset theNumber = left(theNumber, 1) is 0 ? theNumber : REReplaceNoCase(theNumber, "^[0-9]{2}", 0) />
    <!--- // returns 05656 --->
    <cfoutput>#theNumber#</cfoutput>
    
    <hr />
    
    <!--- // a number that starts with zero --->
    <cfset theNumber = "05656" />
    <cfset theNumber = left(theNumber, 1) is 0 ? theNumber : REReplaceNoCase(theNumber, "^[0-9]{2}", 0) />
    <!--- // returns 05656 --->
    <cfoutput>#theNumber#</cfoutput>
    

    If your number always starts with either 0 or 44 you can use

    <cfset theNumber = left(theNumber, 1) is 0 
                        ? theNumber 
                        : REReplaceNoCase(theNumber, "^[4]{2}", 0) /> 
    

    Update: Also, read the comments, there are some good points in there.