Rename two string variables

Let's say I have two string variables:

a = 'LOVE'; b = '....'; 

How to use a regex (or something else the fastest) to combine a + b to do:

 c = 'LOVE'; 

In my case, both lines are 4 characters long, always, and the second line is not a fixed character, I just made it a dot to make it clearer on the screen.

+5
source share
6 answers

You can simply skip the longer line and add one character from both lines to your resulting line at each iteration. I do not think you need a regular expression:

 a = 'LOVE'; b = '....'; var combinedString = ''; var largerLength = Math.max( a.length, b.length ); for( var i = 0; i < largerLength; i++ ) { combinedString += a.charAt(i) + b.charAt(i); }//for() console.log( combinedString ); 

The above code will work for strings of any length. In case you know in advance that both lines have exactly 4 characters, I think the fastest and most efficient way:

 a = 'LOVE'; b = '....'; var combinedString = a.charAt[0] + b.charAt[0] + a.charAt[1] + b.charAt[1] + a.charAt[2] + b.charAt[2] + a.charAt[3] + b.charAt[3]; console.log( combinedString ); 
+9
source

You can use Array#reduce for it

 var a = 'LOVE', b = '....'; c = a.split('').reduce(function (r, v, i) { return r + v + b[i]; }, ''); console.log(c); 
+6
source

How to combine a + b with a regex :

 var a = "LOVE", b = "...."; var result = a.replace(/./g, (match, i) => match + b[i]); console.log(result); 
+1
source

No regex is needed for your problem. You can just do it with a for loop

 a = 'LOVE'; b = '....'; var result = ''; var length = Math.max( a.length, b.length ); for( var i = 0; i <+ length-1; i++ ) { result = result + a.charAt(i); result = result + b.charAt(i); } alert("Result of combined string is :"+ result); 
0
source

You can use the array functions in the array you like (in this example, the string) to iterate over the elements.

 var a = 'LOVE', b = '....', c = Array.prototype.map .call(a, (v, i) => v + b[i]).join(''); console.log(c); 
0
source

If your second line always consists of dots , instead of repeating the same characters in a line, try something like this:

Using a delimiter

 var a = "LOVE"; var delimeter = "."; var result = a.split("").join(delimeter) + delimeter; console.log(result) 

Array conversion + manual concatenation

As an alternative to string.charAt you can try something like this:

Note: you must do a1[i] || "" a1[i] || "" for cases where the value may be undefined. You should also use .toString() to avoid cases where both values ​​are numeric and the result will be padding instead of concatenation.

 var a = 'LOVE'; var b = '....'; var c = ",,,,,,,,,,,"; function mergeStr(a, b) { var a1 = a.split(""); var b1 = b.split(""); var len = Math.max(a.length, b.length) var r = ""; for (var i = 0; i < len; i++) { r += (a1[i] || "").toString() + (b1[i] || "").toString(); } return r; } console.log(mergeStr(a,b)) console.log(mergeStr(a,c)) 
-2
source

All Articles