Retrieve a substring from the end in JavaScript

To extract a substring from the end of a string in JavaScript, you can use a regular expression to get the characters starting from the position which is the length of the string minus the length of the desired substring.

Be aware that JavaScript’s substring method might not handle characters like emojis or surrogate pairs (such as “𠮷”) correctly, as these characters are represented by two code units.

Source Code

/**
 * Extracts a substring from the end of the specified string
 *
 * @param {string} str The string to extract from
 * @param {number} len The length (number of characters) of the substring
 * @returns {string} The extracted substring
 */
const substringFromEnd = (str, len) => {
    if (len < 0) {
        len = 0;
    }

    const strLen = Array.from(str).length;

    if (strLen < len) {
        return str;
    }

    const reg = new RegExp(`^.{${strLen - len}}(.{0,${len}})`, 'u');
    return str.match(reg)?.[1];
};

Validation

Please specify the string and the length (number of characters) of the substring to execute the function.

Enter Arguments

substringFromEnd(
 
,
 );

Validation Results

Follow me!

photo by:Kelly Sikkema