cocacrave cocacrave - 5 months ago 9
Javascript Question

Regex two string variables

Say I have two string variables:

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


How do I use regex (or whatever else is fastest) to combine a + b to make:

c = 'L.O.V.E.';


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

Answer

You can simply loop through the longer string and in each iteration append one character from both strings to your resulting string. I don't think you need any regular expression there:

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 beforehand that both strings are exactly 4 characters long, I think the fastest and most efficient way would be:

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