

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 the longest common consecutive substring between two strings in JavaScript
We are required to write a JavaScript function that takes in two strings. Let’s call them str1 and str2. The function should then find out the longest consecutive string that is common to both the input strings and return that common string.
For example −
If the input strings are −
const str1 = 'ABABC'; const str2 = 'BABCA';
Then the output string should be −
const output = 'BABC';
Example
Following is the code −
const str1 = 'ABABC'; const str2 = 'BABCA'; const findCommon = (str1 = '', str2 = '') => { const s1 = [...str1]; const s2 = [...str2]; const arr = Array(s2.length + 1).fill(null).map(() => { return Array(s1.length + 1).fill(null); }); for (let j = 0; j <= s1.length; j += 1) { arr[0][j] = 0; } for (let i = 0; i <= s2.length; i += 1) { arr[i][0] = 0; } let len = 0; let col = 0; let row = 0; for (let i = 1; i <= s2.length; i += 1) { for (let j = 1; j <= s1.length; j += 1) { if (s1[j - 1] === s2[i - 1]) { arr[i][j] = arr[i - 1][j - 1] + 1; } else { arr[i][j] = 0; } if (arr[i][j] > len) { len = arr[i][j]; col = j; row = i; } } } if (len === 0) { return ''; } let res = ''; while (arr[row][col] > 0) { res = s1[col - 1] + res; row -= 1; col -= 1; } return res; }; console.log(findCommon(str1, str2));
Output
Following is the output on console −
BABC
- Related Questions & Answers
- Finding longest substring between two same characters JavaScript
- Finding longest consecutive joins in JavaScript
- How to find the longest common substring from more than two strings in Python?
- Finding the longest substring uncommon in array in JavaScript
- Finding shared element between two strings - JavaScript
- Longest string consisting of n consecutive strings in JavaScript
- SequenceMatcher in Python for Longest Common Substring.
- Finding all the longest strings from an array in JavaScript
- Finding the common streak in two arrays in JavaScript
- Find the longest common prefix between two strings after performing swaps on second string in C++
- Finding and returning uncommon characters between two strings in JavaScript
- Finding the length of longest vowel substring in a string using JavaScript
- Finding the longest Substring with At Least n Repeating Characters in JavaScript
- Program to print the longest common substring using C++
- Finding gcd of two strings in JavaScript
Advertisements