Vandana Bhat
Vandana Bhat

Reputation: 211

Why can't I swap characters in a javascript string?

I am trying to swap first and last characters of array.But javascript is not letting me swap. I don't want to use any built in function.

function swap(arr, first, last){
    var temp = arr[first];    
    arr[first] = arr[last];
    arr[last] = temp;
}

Upvotes: 21

Views: 28538

Answers (6)

Sazzad
Sazzad

Reputation: 306

Swap characters inside a string requires the string to convert into an array, then the array can be converted into string again:

function swap(arr, first, last){
    arr = arr.split('');    //to array
    var temp = arr[first];    
    arr[first] = arr[last];
    arr[last] = temp;
    arr = arr.join("").toString()    //to string
    return arr;
}

Following usage:

str = "ABCDE"
str = swap(str,1,2)
console.log(str)     //print "ACBDE"

Upvotes: 2

Kirill Shur
Kirill Shur

Reputation: 290

I hope this piece of code will help somebody.

var word =  "DED MOROZ";

var arr = word.split('');

for (var i = 0; i < arr.length/2; i++) {

   var temp = arr[i];

   arr[i] = arr[arr.length - i - 1];

   arr[word.length - i - 1] =  temp;
}

console.log(arr.join(""));

Run this code and your characters will be swapped.

Upvotes: 0

JohnHanr
JohnHanr

Reputation: 233

function swapStr(str, first, last) {
    if (first == last) {
      return str;
    }

    if (last < first) {
      var temp = last;
      last = first;
      first = temp;
    }

    if (first >= str.length) {
      return str;

    }
    return str.substring(0, first) +
      str[last] +

      str.substring(first + 1, last) +

      str[first] +
      str.substring(last + 1);
  }

Upvotes: 1

Dalorzo
Dalorzo

Reputation: 20014

Let me offer my side of what I understood: swapping items of an array could be something like:

var myFish = ["angel", "clown", "mandarin", "surgeon"];
var popped = myFish.pop();
myFish.unshift(popped) // results in ["surgeon", "angel", "clown", "mandarin"]

Regarding swaping first and last letters of an strings could be done using Regular Expression using something like:

"mandarin".replace(/^(\w)(.*)(\w)$/,"$3$2$1")// outputs nandarim ==> m is last character and n is first letter

Upvotes: 3

Oriol
Oriol

Reputation: 288270

Because strings are immutable.

The array notation is just that: a notation, a shortcut of charAt method. You can use it to get characters by position, but not to set them.

So if you want to change some characters, you must split the string into parts, and build the desired new string from them:

function swapStr(str, first, last){
    return str.substr(0, first)
           + str[last]
           + str.substring(first+1, last)
           + str[first]
           + str.substr(last+1);
}

Alternatively, you can convert the string to an array:

function swapStr(str, first, last){
    var arr = str.split('');
    swap(arr, first, last); // Your swap function
    return arr.join('');
}

Upvotes: 26

Zexus
Zexus

Reputation: 173

I just ran your code right out of Chrome, and it seemed to work find for me. Make sure the indices you pass in for "first" and "last" are correct (remember JavaScript is 0-index based). You might want to also try using console.log in order to print out certain variables and debug if it still doesn't work for you.

EDIT: I didn't realize you were trying to manipulate a String; I thought you just meant an array of characters or values.

My code

Upvotes: 2

Related Questions