- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check whether a string ends with some other string - JavaScript
We are required to write a JavaScript function that takes in two strings say, str1 and str2. The function should determine whether or not str1 ends with str2. Our function should return a boolean on this basis.
Here’s our 1st string −
const str1 = 'this is just an example';
Here’s our 2nd string −
const str2 = 'ample';
Example
Following is the code −
const str1 = 'this is just an example'; const str2 = 'ample'; const endsWith = (str1, str2) => { const { length } = str2; const { length: l } = str1; const sub = str1.substr(l - length, length); return sub === str2; }; console.log(endsWith(str1, 'temple')); console.log(endsWith(str1, str2));
Output
This will produce the following output in console −
false true
Advertisements