Nodejs String Swap swapLetters(index)

Here you can find the source of swapLetters(index)

Method Source Code

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;/* www  .  j ava2 s  . c  o 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'));

Related

  1. swap(a, b)
    String.prototype.swap = function(a, b) {
        var array = this.split('');
        var tmp = array[a];
        array[a] = array[b];
        array[b] = tmp;
        return array.join('');
    function permutation(str, start) {
        if (start == str.length - 1) {
    ...
    
  2. swap(l,r)
    var pers=[];
    function permute(s,l,r){
      if(l==r) pers.push(s);
      else {
        for(var i=l;i<=r;i++) {
          s=s.swap(l,i);
          permute(s,l+1,r);
          s=s.swap(l,i);
    String.prototype.swap=function(l,r) {
      return this.split('').map((a,i)=>i==l?this[r]:i==r?this[l]:a).join('');
    permute('abc',0,2);
    console.log(pers);
    
  3. swap_chars(i,j)
    String.prototype.swap_chars = function(i,j) {
        var array_string = this.split("");
        tmp = array_string[i];
        array_string[i] = array_string[j];
        array_string[j] = tmp;
        return array_string.join("");
    };
    
  4. swap_substr(i)
    String.prototype.swap_substr = function(i) {
        return this.substr(0, i) + this.substr(i).split("").reverse().join("");
    };