Verify whether a string concludes with the specified target strings | utilizing JavaScript

Looking to develop a JavaScript function that checks if the last characters of a string match a given target. The function must utilize the .substr() method for this purpose.

function endOfString(str, target) {
  let endCharacters = str.substr(-target.length);
  
  if (endCharacters === target) {
    return true;
  } else {
    return false;
  }
}

console.log(endOfString('Bastian', 'n'));

Answer №1

Give it a shot:

function checkEndOfString(str, target) {
   return str.substring(str.length-target.length) == target;
}

UPDATE:

If you're using modern browsers, you can utilize: string.prototype.endsWith. However, for Internet Explorer, a polyfill is necessary (you can explore which provides the polyfill and does not serve any content to newer browsers; it's also beneficial for other IE-related functions).

Answer №2

Starting from ES6, it is now possible to utilize the endsWith() method on strings. Here's an example:

let mystring = 'exampleString';
//this should return true
console.log(mystring.endsWith('String'));
//this should return true
console.log(mystring.endsWith('g'));
//this should return false
console.log(mystring.endsWith('example'));

Answer №3

Give this a shot...

 function checkEnd(str, target) {
  var strLength = str.length;
  var tarLength = target.length;
  var remaining = strLength - tarLength;
  strEnd = str.substr(remaining);

  if (strEnd == target){
    return true;
     }else{
  return false;
     }  
 return str;
}
checkEnd('Bastian', 'n');

Answer №4

Give this a shot:

function checkEnd(str, target) {
    return str.slice(-target.length) === target;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When an event occurs, have Express make an HTTP call to Angular

In the process of developing an Angular application, I am working on a feature that will enable around a thousand users to connect simultaneously in order to book tickets. However, I only want a specific number of them, let's call it "XYZ", to access ...

Is it possible to add items to your cart based on a matching product ID?

My challenge is to add an item to a list only if it matches the id, ensuring that only one item is added to the cart. I've attempted various methods but React doesn't seem to recognize my item's id. Below is the code excerpt where I'm ...

What is the best way to update the content of a div when it is being hovered over?

On my website I am building, there is a division that contains text. When I hover over the division, I want the text to change from "example" to "whatever". I came across a forum discussing this, but I'm having trouble understanding it. Can someone p ...

A controller in Angular.js that leverages several different services

I'm having trouble injecting multiple services into a controller. Here are my listed files: index.html file: <script src="'./angular/angular.min.js'></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta ...

Switching the displayed image depending on the JSON data received

As a beginner in javascript and jQuery, I am working on displaying JSON results in the browser. My goal is to generate dynamic HTML by incorporating the JSON data. Below is an example of the JSON structure: [{"JobName":"JobDoSomething","JobStatus":2,"JobS ...

Utilize Ant Design TreeSelect to seamlessly integrate API data into its title and value parameters

I am currently working on populating a Tree Select component in ANT Design with data fetched from an API. The response from the API follows this structure: projectData = ProjectData[]; export type ProjectData = { key?: number; projectId: number; ...

Retrieve information from an API and assign the corresponding data points to the graph using Material UI and React

I have 4 different APIs that I need to interact with in order to fetch specific details and visualize them on a bar graph. The data should be organized based on the name, where the x-axis represents the names and the y-axis represents the details (with 4 b ...

jQuery document.ready not triggering on second screen on Android device

Why is jQuery docment.ready not firing on the second screen, but working fine on the first/initial screen? I also have jQuery Mobile included in the html. Could jQuery Mobile be causing document.ready to not work? I've heard that we should use jQuery ...

Using JavaScript to create a search bar: Can "no results found" only show after the user has completed typing their search query?

How can I ensure that the "no match" message only appears after the user has finished typing in their search query, rather than seeing it while they are still typing "De" and the list displays "Demi"? usernameInput.addEventListener("keyup",function(){ ...

Extracting data from a JSON file with the help of Node.js

I've recently delved into node.js and find myself in a bit of a pickle. I have a json file called keyValue.json that looks something like this [ { "key": "key1", "value": "value1" }, { "key": "key2", "value": "value2" } ] I ...

How come my loop is unable to recognize the character in a constant string?

#include<iostream> #include<string> #include<sstream> #include <typeinfo> #include<cmath> #include<vector> #include <algorithm> using namespace std; class CustomString { char *array; public: CustomString( ...

Leveraging the state feature in react-router-dom's Redirect

I have been utilizing the instructions provided by react-router-dom's Redirect in my project. Currently, I have a component that displays the code snippet below: return <Redirect to={{ pathname: '/login', state: { previousPath: path } } ...

Looking to Add Dynamic Website Embed Link?

When a user arrives at the website and the Current Top URL is "https://website.com/?code=https://webbbb.com", I need to dynamically set the iframe URL to "https://webbbb.com" for embedding purposes. This way, I can automatically link my complete other web ...

Adding an HDRi Equirectangle map in ThreeJS requires careful consideration to ensure the scene is properly lit while maintaining a transparent background

How can I incorporate HDRi lighting with an HDR EQUIRECTANGLE Texture into my scene while keeping the image transparent? I am sourcing images from the HDRI Haven website. Can you provide guidance on how to accomplish this? ...

Best method for reusing a component in React?

Here is a simplified code featuring a reusable button component: import React from 'react' import styles from './Button.module.scss' const Button = (props) => { return ( <button type={props.type} className={styles.btn} onC ...

Add numerical identifiers to numerous camera entities

I am working on a three js scene that includes a 3D model, and I would like to incorporate multiple cameras into the model. In order to distinguish between each of the cameras in the scene, I am looking for a way to label them with numbers, possibly near ...

The model seems to have loaded successfully but is not displayed

Struggling to make a model from an .obj file load and be visible in Three.js. New to this, so seeking help! Here is my code so far: const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); ...

The POST request functions flawlessly on the local server, but encounters issues once deployed to Google Cloud Platform

Even though the Axios post request works fine on my local server, it throws a 404 not found error after I deploy the project on Google Cloud. On localhost, all requests are directed to URLs starting with http://localhost:9000/api/..., handling post reques ...

Rejuvenate your Kendo Chart by utilizing a promise to update the DataSource

I am currently facing a challenge in my Angular application where I need to update the data source for multiple charts and then redraw them. The data source is updated through an Angular service that returns a promise. While I am able to successfully upd ...

Issue: The specific module is unable to be located, specifically on the Heroku platform

While my application performs well locally and on a Travis CI build server, it encounters issues when deployed on Heroku. The error message Error: Cannot find module is displayed, leading to app crashes. Here are some details about the npm module: It r ...