Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
ShowAll Questionssorted byDate Posted
frank2anil

# How to remove zeros in the string.

Hi guys,

my problem is there are two strings with some value i need to remove the zeros before the number and add both the strings .

Ex:-

String S=000578;

String j=080554321;

String k=s+j    ( not addition);

k                                 =  s    +     j;

57880554321        =   578+ 80554321;

it means it shoul remove all the zeros before the number.

Some times s=0578;

j=00080554321;

then also the out put should be same as above "k"

Thanks

frank

ani123

can you explain me inn brief were u do this???

tomcollins

Use replaceFirst() on each string to strip the leading zeros, using the regular expression '^0+' which means, "one or more zeros at the start of the string".

k = s.replaceFirst( '^0+', '') + j.replaceFirst( '^0+', '');

Anu Raj.ax1269

Hi frank,

Try this code

String S=000578;

s= s.replace('0', '');

thanks

Anu

frank2anil

Hi ani123,

This actual used in lead object.

Where i had 2 fields country code and phone number.

so what i need if.they enter country code like 91.

And phone number like 999999999.

so it should return 91999999999 .

if they enter country code like 091.

and phone number like 091-999999999.

Then also it shoul return 91999999999  .

Thanks

Frank

tomcollins

Anu, you do realize that the string replace() method would remove ALL zeros from the string, right?

The OP wants to remove leading zeros from a string, which is different than removing all zeros.

ani123

Hi Frank,

Try something in formula field  LIK THIS TO TRIM UR first  3 values OF country code   from ur contact number

TRIM(LEFT( Field_1__c ,3))

Regards,

ANI

VishalParikh
Convert to Int/Dec and back to String:

for example:
James Loghry
You can do this with a regex fairly easy, like so:

`myStr = myStr.replaceFirst('^0+','');`

The regex searches for one or more zeroes at the start of the string and replaces them with an empty string.
JaimeBid
Thanks James! that is the right one. But if by chance there is an space, like 00 0123, it would miss the third 0, so better remove spaces too
Would this work then?
myStr = myStr .replaceAll( '\\s+', '').replaceFirst('^0+','')

Btw this one would not work as requested because if would remove all "0" found, not just the ones at the beggining
String S=000578;
s= s.replace('0', '');