- 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
Finding shared element between two strings - JavaScript
We are required to write a JavaScript function that takes in two strings that may / may not contain some common elements. The function should return an empty string if no common element exists otherwise a string containing all common elements between two strings.
Following are our two strings −
const str1 = 'Hey There!!, how are you'; const str2 = 'Can this be a special string';
Example
Following is the code −
const str1 = 'Hey There!!, how are you'; const str2 = 'Can this be a special string'; const commonString = (str1, str2) => { let res = ''; for(let i = 0; i < str1.length; i++){ if(!str2.includes(str1[i])){ continue; }; res += str1[i]; }; return res; }; console.log(commonString(str1, str2));
Output
Following is the output in the console −
e here h are
Advertisements