Javascript String swapLetters(index)

Description

Javascript String swapLetters(index)


String.prototype.swapLetters = function(index) {
    var words = this.split("");
    var firstLetter = words[index];
    var lastLetter = words[words.length - 1 - index];
    var temp = firstLetter;

    words[index] = lastLetter;/*from  w ww. jav  a 2  s .co  m*/
    words[words.length -1 - index] = temp;
    return words.join("");
};


function rev(string) {
  var sLen = Math.floor(string.length / 2);

  for (var i=0; i < sLen; i++) {
      string = string.swapLetters(i);
  }
  return string;
}


console.log(rev('hello'));



PreviousNext

Related