- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Finding and returning uncommon characters between two strings in JavaScript
- Finding the longest common consecutive substring between two strings in JavaScript
- Finding gcd of two strings in JavaScript
- Difference between two strings JavaScript
- Finding the difference between two arrays - JavaScript
- Sorting 2-D array of strings and finding the diagonal element using JavaScript
- Hamming Distance between two strings in JavaScript
- Finding letter distance in strings - JavaScript
- Finding longest substring between two same characters JavaScript
- Finding Number of Days Between Two Dates JavaScript
- Finding the intersection of arrays of strings - JavaScript
- Finding middlemost element(s) in JavaScript
- Finding the missing number between two arrays of literals in JavaScript
- Finding distance between two points in a 2-D plane using JavaScript
- Finding all the longest strings from an array in JavaScript

Advertisements