user3357528
user3357528

Reputation: 1

How do I duplicate every letter in a string with JS

I'm trying to double my string xyz to xxyyzz in JS but can't get it to return correctly. What am I doing wrong?

<script>
string=["xyz"];
for (var i=0;i<string.length;i++)
{
document.write(string[i]*2);
}
</script>

Upvotes: 0

Views: 939

Answers (4)

Andre Figueiredo
Andre Figueiredo

Reputation: 13425

  1. You didn't declared a string, you declared an array of string with 1-length.

  2. Your are multiplying position of array (string[i]*2), trying concatenating (string[i] + string[i]).

This should work:

var string = 'xyz';

for (var i = 0, len = string.length; i < len; i++) {
    document.write(string[i] + string[i]);
}

Upvotes: 0

j-da
j-da

Reputation: 188

A few problems:

  • You've declared string inside an array, giving string.length a value of 1 as that's the number of elements
  • You can't multiply strings, unfortunately. You need to concatenate them

Here's how I'd do it:

var string = "xyz";
var newString = "";
for (var i = 0; i < string.length; i++)
    newString += string[i] + string[i];
document.write(newString);

Upvotes: 0

Scimonster
Scimonster

Reputation: 33409

var string = "xyz".split('').map(function(s){return s+s}).join('');

I like doing it using array maps instead of for loops. It seems cleaner to me.

Upvotes: 4

Rob Aston
Rob Aston

Reputation: 816

The correct way would be to add the strings together (concatenation) instead of using a multiply by 2 which won't work. See below:

<script type="text/javascript">

var string = ['xyz'];

for (var i = 0, len = string.length; i < len; i++) {
    document.write(string[i] + string[i]);
}

</script>

Upvotes: 0

Related Questions