Last Updated on July 12, 2020 by Sudhir
As you all know, Salesforce used to use a 15 character case-sensitive record ID to uniquely identify any record in the org. But over time, they transitioned over to an 18 character case-insensitive ID, but there are areas where you will still only get the 15 character ID. For example, in reports.
The logic to convert a 15 character ID to 18 characters is not complex. Below are the steps to perform, followed by code samples in Apex and JavaScript.
Consider the 15 character ID 0013k00002crTPa.
- Divide the 15 characters into 3 sets of 5 characters each: 0013k 00002 crTPa
- Invert the characters in each set: k3100 20000 aPTrc
- For each character in a given inverted set, assign a value of 1 if that character is an uppercase character, 0 otherwise: 00000 00000 01100
- We now have a binary representation of each set. Combine each seat to it’s decimal equivalent: 0 0 12
- Now construct an array of 32 values containing the sequence A-Z and 0-5:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5
- Use the decimal number from each set as an index and choose the corresponding character/number from the A-Z 0-5 list above staring with A = 0, B = 1, … 5 = 31:
-
0 = A 8 = I 16 = Q 24 = Y
1 = B 9 = J 17 = R 25 = Z
2 = C 10 = K 18 = S 26 = 0
3 = D 11 = L 19 = T 27 = 1
4 = E 12 = M 20 = U 28 = 2
5 = F 13 = N 21 = V 29 = 3
6 = G 14 = O 22 = W 30 = 4
7 = H 15 = P 23 = X 31 = 5
-
- Using the decimal representation of each set, and taking the corresponding alpha-numeric character, 0 0 12 becomes A A M
- Now take those 3 letters and append to the end of the 15 character ID to get the 18 character ID of 0013k00002crTPaAAM.
JavaScript:
function convertId(input) {
var output;
if (input.length == 15) {
var addon = "";
for (var block = 0; block < 3; block++) {
var loop = 0;
for (var position = 0; position < 5; position++) {
var current = input.charAt(block * 5 + position);
if (current >= "A" && current <= "Z") loop += 1 << position;
}
addon += "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345".charAt(loop);
}
output = (input + addon);
} else {
alert("Error : " + input + " isn't 15 characters (" + input.length + ")");
return;
}
return output;
}
Apex:
Turning a 15 character ID into an 18 character ID is pretty straight forward. It’s almost comical:
String fifteen = '0013k00002crTPa';
Id eighteen = fifteen;
System.debug('15 char: ' + fifteen); //outputs 0013k00002crTPa
System.debug('18 char: ' + eighteen); // outputs 0013k00002crTPaAAM
If you want to make that into a utility method, simply do the following:
public static Id convertId15To18(String fifteen) {
return fifteen;
}