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
  • 984
  • 3
  • 11
  • 35

8 Answers8

7

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
  • 113,687
  • 23
  • 165
  • 188
  • 1
    s.replace(/./g, '$&$&') --way cooler than the rest. Very elegant. Although using the For loop probably more efficient, if there is a lot of input involved. – jdmayfield Jul 28 '23 at 22:51
3

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
  • 10,181
  • 7
  • 62
  • 98
2

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
  • 36,090
  • 8
  • 62
  • 107
1

if you want to make it with a loop, then you have to print s[i]+s[i]; not, s + s.

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

console.log(newS);

that works for me, maybe a little bit hardcoded, but I am new too)) good luck

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
  • 24,354
  • 5
  • 48
  • 79
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,777
  • 2
  • 14
  • 27
-1

You can simply use one of these two methods:

const doubleChar = (str) => str.split("").map(c => c + c).join("");

OR

function doubleChar(str) {
    var word = '';
  for (var i = 0; i < str.length; i++){
    word = word + str[i] + str[i];
  };
  return word;
};
-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