Why can't I change characters in javascript string?

I am trying to swap the first and last characters of an array. But javascript won't let me swap places. I don't want to use a built-in function.

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

      

+3


source to share


4 answers


Because strings are immutable.

Array notation is: designation, method label charAt

. You can use it to get symbols by position, but not to set them.

So, if you want to change some characters, you have to split the string into parts and create the desired newline 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 a string to an array:

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

      

+8


source


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

EDIT: I didn't understand that you are trying to manipulate a string; I thought you just meant an array of characters or values.



My code

+1


source


Let me offer my side of what I understood: replacing array elements could be something like this:

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

      

As for changing the first and last letters of strings, it can be done with a Regular Expression using something like:

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

      

+1


source


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);

      

}

0


source







All Articles