w3resource

JavaScript: Concatenate two strings and return the result

JavaScript Basic: Exercise-64 with Solution

Write a JavaScript program to concatenate two strings and return the result. If the length of the strings does not match, then remove the characters from the longer string.

For example "Python" and "JS" will be "onJS".

Pictorial Presentation:

JavaScript: Concatenate two strings and return the result

Sample Solution:

JavaScript Code:

// Define a function named str_con_cat with parameters str1 and str2
function str_con_cat(str1, str2) {
    // Calculate the minimum length of str1 and str2
    const m = Math.min(str1.length, str2.length);
  
    // Use substring to concatenate the common characters from the end of both strings
    return str1.substring(str1.length - m) + str2.substring(str2.length - m);
}

// Call the function with sample arguments and log the results to the console
console.log(str_con_cat("Python", "JS"));
console.log(str_con_cat("ab", "cdef")); 

Sample Output:

onJS
abef

Live Demo:

See the Pen JavaScript - Concatenate two strings and return the result - basic-ex-64 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Concatenate two strings and return the result

ES6 Version:

 // Define a function named str_con_cat with parameters str1 and str2
const str_con_cat = (str1, str2) => {
    // Use Math.min to find the minimum length between str1 and str2
    const m = Math.min(str1.length, str2.length);
    // Concatenate substrings using substring method and return the result
    return str1.substring(str1.length - m) + str2.substring(str2.length - m);
};

// Call the function with sample arguments and log the results to the console
console.log(str_con_cat("Python", "JS"));
console.log(str_con_cat("ab", "cdef"));

Previous: JavaScript program to create a string using the middle three characters of a given string of odd length.
Next: JavaScript program to test if a string end with "Script". The string length must be greater or equal to 6.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.