How do you extract the last N characters of a string in JavaScript? | A1Lab@FahadM to JavaScriptEnglish •
edit-2
4 days ago

How do you extract the last N characters of a string in JavaScript?

message-square
0

To extract the last n characters of a string in JavaScript without mutating the source string, validate that text is a string and count is a non-negative integer, handle count === 0 explicitly (because text.slice(-0) behaves like text.slice(0) and returns the full string), and slice from the computed start index via text.slice(startIndex). Strings in JavaScript are immutable, so .slice() always returns a new string.


1. Extracting the Last N UTF-16 Characters Safely with .slice()

Validate parameter types and integer bounds inside a try/catch block, return "" when count === 0 or text is empty, and clamp startIndex to 0 so count exceeding text.length returns the full string without error or mutation:

// Extract the last n UTF-16 characters without mutating the original string
function extractLastChars(text, count) {
  try {
    if (typeof text !== "string") {
      throw new TypeError("Expected text to be a string.");
    }

    if (typeof count !== "number" || !Number.isInteger(count) || count < 0) {
      throw new RangeError("Expected count to be a non-negative integer.");
    }

    if (count === 0 || text.length === 0) {
      return "";
    }

    const startIndex = Math.max(0, text.length - count);
    return text.slice(startIndex);
  } catch (error) {
    throw error;
  }
}

// Example usage:
const orderCode = "ORD-2026-9842";
console.log("Last 4 chars:", extractLastChars(orderCode, 4)); // "9842"
console.log("Zero chars:", extractLastChars(orderCode, 0));   // ""
console.log("Exceeds length:", extractLastChars("abc", 10)); // "abc"
console.log("Original untouched:", orderCode);                 // "ORD-2026-9842"
  • Explicit zero handling: Avoids the -0 quirk where str.slice(-0) acts like str.slice(0) and returns the entire string.
  • Non-mutating & bounds-safe: Clamps startIndex with Math.max(0, ...) and preserves the source string.

2. Extracting the Last N Unicode Code Points for Emoji and Surrogates

Because .slice() counts UTF-16 code units, slicing a string containing surrogate pairs (such as emoji) at an odd boundary can split a surrogate pair in half; convert via Array.from(text) first to slice whole Unicode code points non-mutatingly:

// Extract the last n Unicode code points without splitting surrogate pairs
function extractLastCodePoints(text, count) {
  try {
    if (typeof text !== "string") {
      throw new TypeError("Expected text to be a string.");
    }

    if (typeof count !== "number" || !Number.isInteger(count) || count < 0) {
      throw new RangeError("Expected count to be a non-negative integer.");
    }

    if (count === 0 || text.length === 0) {
      return "";
    }

    const codePoints = Array.from(text);
    const startIndex = Math.max(0, codePoints.length - count);
    return codePoints.slice(startIndex).join("");
  } catch (error) {
    throw error;
  }
}

// Example usage:
const statusLine = "Build OK 🚀✨";
console.log("Last 2 code points:", extractLastCodePoints(statusLine, 2)); // "🚀✨"
console.log("Original untouched:", statusLine);                         // "Build OK 🚀✨"
  • Surrogate-pair aware: Array.from(text) iterates Unicode code points rather than raw 16-bit code units.
  • Immutable output: Joins the sliced code points into a new string without modifying statusLine.

TL;DR: Guard typeof text === "string" and Number.isInteger(count) && count >= 0, return "" when count === 0, and use text.slice(Math.max(0, text.length - count)) (or Array.from(text) for Unicode code points) with explanation and code paired together.