Checking if one string can be achieved from another with single tweak in JavaScript


We are required to write a JavaScript function that takes in two strings of characters lets call them str1 and str2.

The function should check whether we can form str2 from str1 by deleting exactly one character from str1. If we can do so the function should return true, false otherwise.

For example −

If the input strings are −

const str1 = 'chemistty';
const str2 = 'chemisty';

Then the output should be −

const output = true;

Example

Following is the code −

const str1 = 'chemistty';
const str2 = 'chemisty';
const stringSimilarity = (str1 = '', str2 = '') => {
   if(str1.length - str2.length !== 1){
      return false;
   };
   for(let i = 0; i < str1.length; i++){
      const desired = str1.substring(0, i) + str1.substring(i + 1, str1.length);
      if(desired === str2){
         return true;
      };
   };
   return false;
};
console.log(stringSimilarity(str1, str2));

Output

Following is the console output −

true

Updated on: 22-Jan-2021

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements