3

JS:

var str = "SLA-UPsdfdsfdsfG-4HR-4ON";
var res = str.substr(-7, 3);

Output: 4HR

What is the alternative for Substr in apex which is starting from end due to minus starting index.

4

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.

  • Of the answers given so far, I think this one is the most intuitive translation from the Javascript function. +1 from me. – Derek F Sep 21 '17 at 12:37
  • @DerekF but Input value is negative 7 according to question ,Not positive 7, But i appreciate hemant-jain for the effort to answering. – NITHESH K Sep 21 '17 at 12:39
  • 1
    @NITHESHK you're correct, though for me the most important part is that the absolute value of the numbers is the same. .right(7) is a smaller intuitive jump in my mind than .mid(str.length() - 7, 3) is. – Derek F Sep 21 '17 at 12:45
  • @DerekF Yes, Most Important part was (-7) , otherwise answer could be so easy to say. – NITHESH K Sep 21 '17 at 12:53
5

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);
2

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);

EDIT

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);
-1

You could also use lastIndexOfChar(character, endIndex) to find the appropriate - delimited group

  • That is incorrect. In this case, the string starts with 4, and the last instance of that character is later in the string. – Adrian Larson Sep 21 '17 at 17:02
  • "to find the appropriate - delimited group" ie lastindexofchar('-')-3 is the start position – adasghasrg Sep 21 '17 at 17:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.