var str = "SLA-UPsdfdsfdsfG-4HR-4ON"; var res = str.substr(-7, 3);
What is the alternative for Substr in apex which is starting from end due to minus starting index.
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.Sign up to join this community
Another way of doing it is as follows:
You can use a combination of Right and Substring method to achieve the desired output in Apex. Below code for your reference.
String str = 'SLA-UPsdfdsfdsfG-4HR-4ON'; String res = str.right(7).substring(0, 3); System.debug('res is::'+res);
The result would be 4HR for the above code.
You can use the String Mid method in Apex to extract a part of the string by specifying the starting index from and how many characters you need.
If you want to specify the starting index from the end of the string, then you can try something like
yourString.mid( yourString.length() - index, numberOfChars);
Unfortunately, there is no equivalent in Apex. You'll find the String class documentation here.
A workaround would be to use the Apex
substring(startIndex, endIndex) method.
A code equivalent would be:
Integer startIndex = -7; Integer nbCharacters = 3; String str = 'SLA-UPsdfdsfdsfG-4HR-4ON'; startIndex = startIndex < 0 ? str.length() + startIndex : startIndex; String res = str.substring(startIndex,startIndex + nbCharacters);
As @VamsiKrishna said, there is also the
mid(startIndex, length) method.
Using, this method, the last line of code would be:
String res = str.mid(startIndex,nbCharacters);