Change two-character position in javascript

1

When using the language C , we can easily change two characters of a string place, just do:

aux = str[i];
str[i] = str[j];
str[j] = aux;
  

For example: "ABCD" would be "ABDC"

However, I'm having a hard time doing this using javascript. Does anyone know a method that does just that?

    
asked by anonymous 22.01.2018 / 17:57

2 answers

5

In Javascript it is possible to do the same thing, however it is necessary to break string to array previously using the split and then merge with join . Because the string is immutable (immutable values (unable to change or mutate) are primitive values - numbers, strings, booleans, nulls, undefined). While the mutable are all other objects. They are generally referred to as reference types because the object's values are references to the location in memory of which the value resides.)

var str = 'ABCD'.split('');
var i = 1;
var j = 2;

var aux = str[i];    
str[i] = str[j];
str[j] = aux;    
str = str.join('');
console.log(str);

Example: link

    
22.01.2018 / 18:11
-1

You can do this:

var a = "abcd"
a.replace(a[3], a[2]).replace(a[2], a[3])
    
22.01.2018 / 18:12