javascript2016 - 2 years ago 100
Javascript Question

# How to combine(iterate through) 2 strings, mixing the letters in each string with different length?

EDIT: the output should be t1h2i3s4oneislong

I am trying to write a function which returns a new word,combining the letters in 2 words which are being passed the function. If word1 is hello and word2 is 12345 it should return h1e2l3l4o5 - mixing all the letters of both words. The problem is that if one word is longer than the other one, I get undefinedundefinedundefined etc.

I thought I could just ask is word1.length

Could someone explain why this doesn't work (I am learning) and how I could make it work? Thank you!!

``````function creatingWord(one,two){
var string="";
if (one.length==1 &&two.length==1){
string=one+two;
}
else if (one.length==two.length){
for (var i=0; i<one.length;i++){
string+=one[i];
string+=two[i];
}
}
else if (one.length>two.length){
for (var j=0; j<one.length;j++){
string+=one[j];
string+=two[j];
}
}
return string;
}

var result = creatingWord('thisoneislong', '1234');
result;
``````

I think there are two possible answers here, depending on what you want the output to be.

This code gives you the output "t1h2i3s4oneislong" (continuing with the longer word once the other is exhausted):

``````function creatingWord(one, two){
var output = "";
for (var i = 0; i < Math.max(one.length, two.length); i++) {
if (one.length > i) {
output += one[i];
}
if (two.length > i) {
output += two[i];
}
}
return output;
}
``````

Here's a version that gives the output "t1h2i3s4" (truncates to the smaller word):

``````function creatingWord(one, two){
var output = "";
for (var i = 0; i < Math.min(one.length, two.length); i++) {
output += one[i] + two[i];
}
return output;
}
``````

EDIT:

Answering a comment below, here's a version that takes a variable number of arguments:

``````// takes a variable number of words
function creatingWord() {
var output = "";
var words = Array.prototype.slice.call(arguments);

var maxLength = 0;
for (var i = 0; i < words.length; i++) {
var word = words[i];
if (word.length > maxLength) {
maxLength = word.length;
}
}

for (var i = 0; i < maxLength; i++) {
for (var j = 0; j < words.length; j++) {
var word = words[j];
if (word.length > i) {
output += word[i];
}
}
}

return output;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download