Stef
Stef

Reputation: 139

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

Upvotes: 3

Views: 694

Answers (2)

user7972303
user7972303

Reputation: 11

This reReplace() can be run on any string, will only modify and replace with 0 if the string starts with 44.

<cfscript>
   phoneNumber = "44556677";
   phoneNumber = reReplace(phoneNumber, "^44", "0");
   writeOutput(phoneNumber);
</cfscript>

Upvotes: 1

Alex Baban
Alex Baban

Reputation: 11702

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.

Upvotes: 5

Related Questions