Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

Lodash _.endsWith() String Method

Posted in lodash Tutorial
Updated on Oct 30, 2024
By Mari Selvan
👁️ 24 - Views
⏳ 4 mins
💬 1 Comment
Lodash _.endsWith() String Method

Photo Credit to CodeToFun

🙋 Introduction

In JavaScript, string manipulation is a common task, and having efficient tools can greatly simplify development. Lodash, a popular utility library, provides a variety of helpful functions for working with strings. Among these functions is _.endsWith(), which allows developers to easily check if a string ends with a specified target string or character.

This method offers a convenient and reliable solution for string validation and processing.

🧠 Understanding _.endsWith() Method

The _.endsWith() method in Lodash checks if a given string ends with the specified target string or character. This functionality is particularly useful for tasks such as file extension validation, URL parsing, or suffix checking.

💡 Syntax

The syntax for the _.endsWith() method is straightforward:

syntax.js
Copied
Copy To Clipboard
_.endsWith(string, target, [position=string.length])
  • string: The string to search within.
  • target: The target string or character to check for.
  • position (Optional): The position within the string to search up to.

📝 Example

Let's dive into a simple example to illustrate the usage of the _.endsWith() method:

example.js
Copied
Copy To Clipboard
const _ = require('lodash');

const str = 'Hello, world!';
const endsWithWorld = _.endsWith(str, 'world!');

console.log(endsWithWorld);
// Output: true

In this example, _.endsWith() checks if the string str ends with the target string world!, returning true.

🏆 Best Practices

When working with the _.endsWith() method, consider the following best practices:

  1. Validate File Extensions:

    Use _.endsWith() to validate file extensions, ensuring that uploaded files conform to expected formats.

    example.js
    Copied
    Copy To Clipboard
    const fileName = 'document.pdf';
    const isValidFile = _.endsWith(fileName, '.pdf');
    
    console.log(isValidFile);
    // Output: true
  2. Check URL Endings:

    Verify if a URL ends with a specific path or extension, aiding in URL parsing and validation.

    example.js
    Copied
    Copy To Clipboard
    const url = 'https://example.com/page.html';
    const isHtmlPage = _.endsWith(url, '.html');
    
    console.log(isHtmlPage);
    // Output: true
  3. Suffix Checking:

    Efficiently check if strings end with certain suffixes, facilitating data processing and validation.

    example.js
    Copied
    Copy To Clipboard
    const items = ['apple', 'banana', 'kiwi'];
    const endsWithI = items.filter(item => _.endsWith(item, 'i'));
    
    console.log(endsWithI);
    // Output: ['kiwi']

📚 Use Cases

  1. File Type Validation:

    _.endsWith() can be used to validate file types based on their extensions, ensuring compatibility and security in file uploads.

    example.js
    Copied
    Copy To Clipboard
    const uploadedFile = /* ...fetch uploaded file object... */;
    const isImageFile = _.endsWith(uploadedFile.name, '.jpg') || _.endsWith(uploadedFile.name, '.png');
    
    console.log(isImageFile);
  2. URL Routing:

    When implementing URL routing logic, _.endsWith() can help identify specific paths or extensions, directing users to the appropriate resources.

    example.js
    Copied
    Copy To Clipboard
    const requestedPath = /* ...extract requested path from URL... */;
    if (_.endsWith(requestedPath, '.html')) {
        // Serve HTML page
    } else if (_.endsWith(requestedPath, '.css')) {
        // Serve CSS file
    } else {
        // Handle other cases
    }
  3. Data Filtering:

    In data processing tasks, _.endsWith() can assist in filtering out records based on specific suffixes or endings.

    example.js
    Copied
    Copy To Clipboard
    const data = /* ...fetch data from API or database... */;
    const filteredData = data.filter(item => _.endsWith(item.url, '.pdf'));
    
    console.log(filteredData);

🎉 Conclusion

The _.endsWith() method in Lodash provides a reliable solution for checking if a string ends with a specified target string or character. Whether validating file extensions, parsing URLs, or filtering data, this method offers convenience and efficiency in string manipulation tasks.

By adhering to best practices and exploring diverse use cases, you can harness the full potential of the _.endsWith() method in your Lodash projects.

👨‍💻 Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy