1

I need string Double each letter in a string

abc -> aabbcc

i try this

var s = "abc";
for(var i = 0; i < s.length  ; i++){
   console.log(s+s);
}

o/p

>     abcabc    
>     abcabc  
>     abcabc

but i need

aabbcc

help me

Arthi
  • 974
  • 3
  • 11
  • 35

6 Answers6

6

Use String#split , Array#map and Array#join methods.

var s = "abc";

console.log(
  // split the string into individual char array
  s.split('').map(function(v) {
    // iterate and update
    return v + v;
    // join the updated array
  }).join('')
)

UPDATE : You can even use String#replace method for that.

var s = "abc";

console.log(
  // replace each charcter with repetition of it
  // inside substituting string you can use $& for getting matched char
  s.replace(/./g, '$&$&')
)
Pranav C Balan
  • 110,383
  • 23
  • 155
  • 178
2

You need to reference the specific character at the index within the string with s[i] rather than just s itself.

var s = "abc";
var out = "";
for(var i = 0; i < s.length  ; i++){
   out = out + (s[i] + s[i]);
}

console.log(out);
James Monger
  • 9,412
  • 6
  • 52
  • 89
1

I have created a function which takes string as an input and iterate the string and returns the final string with each character doubled.

var s = "abcdef";

function makeDoubles(s){

  var s1 = "";
  for(var i=0; i<s.length; i++){
    s1 += s[i]+s[i];
  }
  return s1;
  
}

alert(makeDoubles(s));
void
  • 34,922
  • 8
  • 55
  • 102
0

console.log(s+s);, here s holds entire string. You will have to fetch individual character and append it.

var s = "abc";
var r = ""
for (var i = 0; i < s.length; i++) {
  var c = s.charAt(i);
  r+= c+c
}

console.log(r)
Rajesh
  • 22,581
  • 5
  • 41
  • 70
0
var doubleStr = function(str) {
    str = str.split('');
    var i = 0;

    while (i < str.length) {
        str.splice(i, 0, str[i]);
        i += 2;
    }

    return str.join('');
};
Eugene Tsakh
  • 2,645
  • 2
  • 13
  • 26
-2

function doubleChar(str) {
  
  let sum = [];
  
  for (let i = 0; i < str.length; i++){
    
   let result = (str[i]+str[i]);
   
   sum = sum + result;

  }
  
   return sum;

}

console.log (doubleChar ("Hello"));
JJJ
  • 1
  • 1