function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
EzmoEzmo 

If function "if starts with"

Hi all,

 

Just a quick one which I'm sure is really easy but I've been wracking my brains for a few hours on this one. 

 

I want to do an if function that would read along the lines of "If string x starts with string y".

 

Any help would be great!

 

Many thanks

 

Eran

Best Answer chosen by Admin (Salesforce Developers) 
SLockardSLockard

Also, there are other ways, one is much easier too.

 

String x = 'ABCDEFGhello';
String y = 'ABCDEFG';

Boolean result = x.startsWith(y);
system.debug(result);

if (result)
{
 system.debug('yes');   
}
else
{
 system.debug('no');
}

Integer r = x.indexof(y);

if (r == 0)
{
 system.debug('yes');
}
else
{
 system.debug('no');
}

 Use whichever one you'd like.

All Answers

SLockardSLockard

Here's some logic that works, hope this helps!

 

String x = 'ABCDEFGhello';
String y = 'ABCDEFG';

String result = x.substring(0,y.length());
system.debug(result);

if (result == y)
{
 system.debug('yes');   
}
else
{
 system.debug('no');
}

 

SLockardSLockard

Also, there are other ways, one is much easier too.

 

String x = 'ABCDEFGhello';
String y = 'ABCDEFG';

Boolean result = x.startsWith(y);
system.debug(result);

if (result)
{
 system.debug('yes');   
}
else
{
 system.debug('no');
}

Integer r = x.indexof(y);

if (r == 0)
{
 system.debug('yes');
}
else
{
 system.debug('no');
}

 Use whichever one you'd like.

This was selected as the best answer
EzmoEzmo

This works nicely, thanks muchly! :)

 

 

I'll get all this logic stuff one day lol.