Program to append two given strings such that, if the concatenation creates a double character then omit one of the characters - JavaScript

We are required to write a JavaScript function that takes in two strings and concatenates the second string to the first string.

If the last character of the first string and the first character of the second string are the same then we have to omit one of those characters. Let's say the following are our strings in JavaScript ?

Problem Example

const str1 = 'Food';
const str2 = 'dog';
// Expected output: 'Foodog' (last 'd' of 'Food' matches first 'd' of 'dog')

Solution

Let's write the code for this function ?

const str1 = 'Food';
const str2 = 'dog';

const concatenateStrings = (str1, str2) => {
    const { length: l1 } = str1;
    const { length: l2 } = str2;
    
    if(str1[l1 - 1] !== str2[0]){
        return str1 + str2;
    };
    
    const newStr = str2.substr(1, l2 - 1);
    return str1 + newStr;
};

console.log(concatenateStrings(str1, str2));

Output

Foodog

How It Works

The function checks if the last character of the first string matches the first character of the second string. If they match, it removes the first character from the second string before concatenation to avoid duplication.

Additional Examples

// Different test cases
console.log(concatenateStrings('Hello', 'world'));  // No duplicate
console.log(concatenateStrings('cat', 'tail'));     // Duplicate 't'
console.log(concatenateStrings('sun', 'noon'));     // Duplicate 'n'
console.log(concatenateStrings('a', 'apple'));      // Duplicate 'a'

Output

Helloworld
catail
sunoon
apple

Conclusion

This function efficiently handles string concatenation while avoiding duplicate characters at the junction point. It uses string comparison and substring methods to create clean concatenated results.

Updated on: 2026-03-15T23:18:59+05:30

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements