- 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 longest substring between two same characters JavaScript
We are required to write a JavaScript function that takes in a string. The function should find and return the length of the longest substring that is sandwiched between two same letters.
For example −
If the input string is −
const str = 'avbghvh';
Then the output should be −
const output = 3;
because the desired longest substring is 'bgh' between two v's.
Example
const str = 'avbghvh'; const longestSub = (str = '') => { const map = new Map(); let max = -1; for(let i = 0; i < str.length; i++){ if(map.has(str.charAt(i))){ max = Math.max(max, i - map.get(str.charAt(i)) - 1); }else{ map.set(str.charAt(i), i); }; }; return max; }; console.log(longestSub(str));
Output
This will produce the following output −
3
- Related Articles
- Finding the longest common consecutive substring between two strings in JavaScript
- Finding the longest Substring with At Least n Repeating Characters in JavaScript
- Finding the longest substring uncommon in array in JavaScript
- Longest Substring with At Most Two Distinct Characters in C++
- How to get substring between two similar characters in JavaScript?
- Finding and returning uncommon characters between two strings in JavaScript
- Largest Substring Between Two Equal Characters in a string in JavaScript
- Longest Substring Without Repeating Characters in Python
- Finding the length of longest vowel substring in a string using JavaScript
- Longest string with two distinct characters in JavaScript
- Longest Substring with At Least K Repeating Characters in C++
- Longest Substring with At Most K Distinct Characters in C++
- Program to find largest substring between two equal characters in Python
- Finding the longest valid parentheses JavaScript
- Finding longest consecutive joins in JavaScript

Advertisements