- 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
Function to check two strings and return common words in JavaScript
We are required to write a JavaScript function that takes in two strings as arguments. The function should then check the two strings for common characters and prepare a new string of those characters.
Lastly, the function should return that string.
The code for this will be −
Example
const str1 = "IloveLinux"; const str2 = "weloveNodejs"; const findCommon = (str1 = '', str2 = '') => { const common = Object.create(null); let i, j, part; for (i = 0; i < str1.length - 1; i++) { for (j = i + 1; j <= str1.length; j++) { part = str1.slice(i, j); if (str2.indexOf(part) !== −1) { common[part] = true; } } } const commonEl = Object.keys(common); return commonEl; }; console.log(findCommon(str1, str2));
Output
And the output in the console will be −
[ 'l', 'lo', 'lov', 'love', 'o', 'ov', 'ove', 'v', 've', 'e' ]
- Related Articles
- Common Words in Two Strings in Python
- Python program to remove words that are common in two Strings
- Common words among tuple strings in Python
- Joining two strings with two words at a time - JavaScript
- Finding the longest common consecutive substring between two strings in JavaScript
- Common Character Count in Strings in JavaScript
- How to extract the strings between two words in R?
- Function to calculate the least common multiple of two numbers in JavaScript
- Compare Strings in JavaScript and return percentage of likeliness
- Python program to find uncommon words from two Strings
- Count common characters in two strings in C++
- Count common subsequence in two strings in C++
- Comparing objects in JavaScript and return array of common keys having common values
- Program to multiply two strings and return result as string in C++
- How to check similarity between two strings in MySQL?

Advertisements