-1

I have an array of strings,

["item1", "item2"] 

I'd like to change my array to

["showItem1", "showItem2"]
Wex
  • 15,539
  • 10
  • 64
  • 107

4 Answers4

3

The most easy to understand way of doing exactly what you ask for is probably something like this:

var items = ["item1", "item2"];

​for (var i=0;i<items.length;i+=1) {
   items[i] = "show" + items[i].charAt(0).toUpperCase() + items[i].substring(1);
}

console.log(items); // prints ["showItem1", "showItem2"] 

Explanation: build a new string consisting of the string "show" + the first character converted to uppercase + the remainder of the string (everything after the first character, which has index 0)

Strille
  • 5,741
  • 2
  • 26
  • 40
1

Strings are array-like. You could do this:

var arr = ['item1', 'item2'];
for (var i=0, l=arr.length; i<l; i++) {
  var letters = arr[i].split('');
  arr[i] = 'show' + letters.shift().toUpperCase() + letters.join('');
}

Demo: http://jsbin.com/asivec/1/edit

elclanrs
  • 92,861
  • 21
  • 134
  • 171
1
arr.map(function(i) {
  return 'show' + i.charAt(0).toUpperCase() + i.slice(1);
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map supported in Chrome, Firefox, IE9 and others.

Devs love ZenUML
  • 11,344
  • 8
  • 53
  • 67
0

Here is a reusable firstCharLowerToUpper() function I wrote for that task.

LIVE DEMO

<!DOCTYPE html>
<html>
  <head>
    <style>
      span{
        color:red;
      }
    </style>
  </head>
  <body>
    <div>this is the text: 
      <span id="spn">
        javascript can be very fun
      </span>
    </div>
    <br/>
    <input type="button" value="Click Here" onClick="change()"/>
    <script> 
      function firstCharLowerToUpper(x)
      {
        var ar = x;
        for (var i = 0; i < ar.length; i++)
        {
          ar[i] = ar[i].charAt(0).toUpperCase() + ar[i].substr(1);
        }
        // join to string just to show the result
        return ar.join('\n');
      }
      function change()
      {
        var ar =  ["javascript ", "can ","be ","very ","fun" ];
        var newtxt = firstCharLowerToUpper(ar);
        document.getElementById("spn").innerHTML = newtxt;
      }
    </script>
  </body>
</html>
Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52