Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 287
cocacrave Avatar asked Jun 22 '16 12:06

cocacrave


2 Answers

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 );
like image 107
Mohit Bhardwaj Avatar answered Nov 15 '22 02:11

Mohit Bhardwaj


You could 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);
like image 40
Nina Scholz Avatar answered Nov 15 '22 04:11

Nina Scholz