- Trending Categories
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 for specific beginning or ending letters in a JavaScript function
We are required to write a JavaScript function that takes in two strings. Let’s call them str1 and str2.
Our function should check either str1 starts with str2 or it ends with str2. If this is the case, we should return true otherwise we should return false.
Example
Following is the code −
const str = 'this is an example string'; const startsOrEndsWith = (str1 = '', str2 = '') => { if(str2.length > str1.length){ return false; }; if(str1 === str2){ return true; }; const { length: l1 } = str1; const { length: l2 } = str2; const startPart = str1.substring(0, l2); const endPart = str1.substring(l1 - l2, l1); return startPart === str2 || endPart === str2; }; console.log(startsOrEndsWith(str, 'hel')); console.log(startsOrEndsWith(str, 'ing')); console.log(startsOrEndsWith(str, 'thi'));
Output
Following is the output on console −
false true true
Advertisements