Lodash _.endsWith() Method

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 6 Examples + 3 Try It
String utilities

What You’ll Learn

By the end of this tutorial, you’ll reliably test whether strings end with a target suffix using Lodash’s _.endsWith() method.

01

Core Syntax

Call _.endsWith(string, target, position).

02

Boolean Result

Returns true or false—never mutates.

03

File Extensions

Validate .pdf, .png, and upload rules.

04

Position Arg

Search only up to an index with the optional third parameter.

05

vs startsWith

Pair with _.startsWith for prefix/suffix checks.

06

Production Tips

Prefer case normalization when extensions may vary in case.

What Is _.endsWith()?

_.endsWith() checks whether a string ends with a given target substring. It returns a boolean—true when the target matches the tail of the string (or the slice up to position), and false otherwise. It mirrors the native String.prototype.endsWith with Lodash’s consistent API and edge-case handling.

💡
Beginner tip

Think of _.endsWith(fileName, '.pdf') as “is this a PDF file?” without writing manual slice logic.

Suffix checks appear in upload validators, static asset routers, autocomplete filters, and anywhere you branch logic based on how a path or filename ends.

📝 Syntax

Provide the haystack string, the suffix to test, and an optional search position:

javascript
_.endsWith(string, target, [position=string.length])

Syntax Rules

  • string — the string to search within.
  • target — the suffix to match at the end (or at position).
  • position — optional index to treat as the effective end of the string.
  • Return value — boolean true or false.
  • Case sensitive.PDF and .pdf are different; normalize case if needed.
javascript
import endsWith from "lodash/endsWith";

const fileName = "report.pdf";
const isPdf = endsWith(fileName, ".pdf");
// -> true

⚡ Quick Reference

TaskCode patternResult
Basic suffix_.endsWith(str, 'world!')true/false
File extension_.endsWith(name, '.png')Image check
With position_.endsWith('abc', 'b', 2)Search up to index
Filter arrayitems.filter(i => _.endsWith(i, 'i'))Suffix matches
Prefix check_.startsWith(str, 'http')Complement helper
Nativestr.endsWith(target)ES2015 equivalent
Returns
boolean

true or false

Mutates?
No

Read-only check

Complement
_.startsWith()

Prefix check

Optional
position

Cap search index

🧰 Parameters

Every argument to _.endsWith() and what it controls:

string Required

The string to inspect. Coerced to string if needed.

_.endsWith('hello!', '!')
target Required

The substring expected at the end. Empty target matches any string.

_.endsWith(url, '.html')
position Optional

Index treated as the end of the string for matching. Defaults to string.length.

_.endsWith('abc', 'b', 2)
return value Boolean

true when the target matches the suffix; otherwise false.

// -> true

For case-insensitive extension checks, normalize with _.toLower() on both strings first.

Examples Gallery

Practical _.endsWith() patterns with copy-ready code, sample output, and interactive Try It Yourself labs.

📚 Getting Started

Test whether a string ends with a target suffix.

Example 1 — Check a greeting suffix

See whether a phrase ends with world!

javascript
import endsWith from "lodash/endsWith";

const str = "Hello, world!";
const match = endsWith(str, "world!");

console.log(match);
// -> true
Try It Yourself

How It Works

Lodash compares the tail of str against the target length.

Example 2 — Validate a PDF extension

Accept only documents ending with .pdf.

javascript
import endsWith from "lodash/endsWith";

const fileName = "document.pdf";
const isPdf = endsWith(fileName, ".pdf");

console.log(isPdf);
// -> true
Try It Yourself

How It Works

A simple guard for upload validators and download buttons.

Example 3 — Filter fruits ending with i

Use endsWith inside Array.filter for suffix rules.

javascript
import endsWith from "lodash/endsWith";

const items = ["apple", "banana", "kiwi"];
const endsWithI = items.filter((item) => endsWith(item, "i"));

console.log(endsWithI);
// -> ["kiwi"]
Try It Yourself

How It Works

Boolean helpers compose cleanly with array methods.

Example 4 — Detect an HTML page URL

Branch routing logic when a path ends with .html.

javascript
import endsWith from "lodash/endsWith";

const url = "https://example.com/page.html";
const isHtml = endsWith(url, ".html");
// -> true

How It Works

The check looks only at the tail of the URL string—for real routing, combine with the URL API to read pathname safely.

Example 5 — Use the position parameter

Search only up to a specific index in the string.

javascript
import endsWith from "lodash/endsWith";

const value = "abc";
console.log(endsWith(value, "b", 2)); // -> true
console.log(endsWith(value, "c", 2)); // -> false

How It Works

position caps how much of the string is considered—only characters before that index participate in the suffix test.

🚀 Beyond the Basics

Native equivalents and related helpers.

Example 6 — Native String.endsWith alternative

Modern JavaScript includes the same capability on strings.

javascript
import endsWith from "lodash/endsWith";

const str = "archive.zip";

// Lodash
console.log(endsWith(str, ".zip")); // -> true

// Native ES2015
console.log(str.endsWith(".zip")); // -> true

How It Works

Reach for Lodash when you want a consistent functional style across utilities; native is fine in modern runtimes.

🧠 How _.endsWith() Works

1

Coerce arguments

Lodash converts string and target to strings.

Input
2

Resolve position

Use provided position or default to string length.

Bounds
3

Slice effective end

Consider only characters up to the resolved position.

Slice
4

Compare tail

Match the last target.length characters against target.

Compare
=

Boolean returned

true when the suffix matches; false otherwise. No string mutation.

📝 Notes

  • _.endsWith() is case-sensitive unless you normalize case first.
  • Empty target matches any string (same as native behavior).
  • The optional position lets you test prefixes of the string as if they were the full length.
  • Pair with _.startsWith() for full prefix/suffix validation.
  • Returns false for non-matching suffixes without throwing.
  • Import lodash/endsWith for tree-shaking.

Conclusion

_.endsWith() is a focused boolean helper for suffix checks: file types, URL endings, and filtered collections. Keep case normalization in mind and use the position parameter when you need partial-string semantics.

Next, secure your output with _.escape() for HTML entity encoding.

💡 Best Practices

✅ Do

  • Normalize case for extension checks when users vary casing
  • Use inside filter() for suffix-based lists
  • Combine with startsWith for protocol + extension rules
  • Import lodash/endsWith for small bundles
  • Document allowed extensions in one constants module

❌ Don’t

  • Rely on endsWith for MIME-type security alone
  • Forget that .PDF and .pdf differ without toLower
  • Use endsWith when you need anywhere-in-string search (use includes)
  • Assume position defaults are obvious to all readers—comment them
  • Parse complex URLs with only endsWith—use URL API when possible

Key Takeaways

Knowledge Unlocked

Five things to remember about _.endsWith()

Use these points whenever you test string suffixes in JavaScript.

5
Core concepts
📄 02

Extensions

Validate file suffixes.

Pattern
📏 03

position

Optional end index.

API
🔄 04

startsWith

Check prefixes too.

Related
🔒 05

escape

Next: HTML safety.

Next step

❓ Frequently Asked Questions

_.endsWith() returns true when a string ends with the specified target substring, optionally up to a given position index.
Yes. .pdf and .PDF are different. Use _.toLower() on both values if you need case-insensitive matching.
position is the index treated as the end of the string for the check. It defaults to string.length.
_.includes() checks for a substring anywhere. _.endsWith() only matches a suffix at the end (or at position).
Yes. Lodash endsWith mirrors String.prototype.endsWith for typical use cases.
It is fine for quick extension guards, but combine with MIME checks and server-side validation for security.
Did you know?

Lodash _.endsWith() mirrors native String.prototype.endsWith, including the optional position argument—so _.endsWith('abc', 'b', 2) is true while _.endsWith('abc', 'c', 2) is false. Pair with _.startsWith() for full prefix/suffix checks.

Practice _.endsWith() in the Live Editor

Open the Try It editor, run the examples, and experiment with your own strings.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful