Smart concatenation of strings in JavaScript

We need to write a JavaScript function that concatenates two strings with a smart approach. If the last character of the first string matches the first character of the second string, we omit one of those duplicate characters to avoid redundancy.

Problem Statement

When concatenating strings like "Food" and "dog", a simple join would give "Fooddog". However, since both strings share the character 'd' at the junction, smart concatenation removes the duplicate to produce "Foodog".

Example

Here's how to implement smart string concatenation:

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));
Foodog

How It Works

The function compares the last character of the first string with the first character of the second string. If they match, it removes the first character from the second string before concatenation.

More Examples

console.log(concatenateStrings("Hello", "oWorld"));  // Duplicate 'o'
console.log(concatenateStrings("Java", "Script"));   // No duplicates
console.log(concatenateStrings("Test", "ing"));      // No duplicates
console.log(concatenateStrings("Cat", "terpillar")); // Duplicate 't'
HelloWorld
JavaScript
Testing
Caterpillar

Edge Cases

// Handle empty strings
console.log(concatenateStrings("", "hello"));   // Empty first string
console.log(concatenateStrings("hello", ""));   // Empty second string
console.log(concatenateStrings("a", "a"));      // Single character match
hello
hello
a

Conclusion

Smart concatenation prevents character duplication at string boundaries, creating cleaner results. This technique is useful for building compound words or joining path segments where overlapping characters are common.

Updated on: 2026-03-15T23:19:00+05:30

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements