Change position of two characters in javascript

Asked

Viewed 842 times

1

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

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

For example: "ABCD" would look "ABDC"

however, I’m having a hard time doing this using javascript. Anyone knows a method that does just that?

  • That’s not exactly what I wanted. I edited the question to make it clear

2 answers

5


In Javascript it is possible to do the same way, but it is necessary to break the string for array previously using the functions of split and then unite with Join. Because the string is immutable (immutable values (unable to change or mutate) are primitive values - numbers, strings, boolean, null, undefined). While the changeables are all other objects. They are usually referred to as reference types because the object 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: https://jsfiddle.net/xvwfnmd2/

  • It’s necessary... because the guy string is immutable in Javascript, while the type array is mutable. This information is required in the answer :D

  • I’ll adjust. Thank you

-1

You can do it like this:

var a = "abcd"
a.replace(a[3], a[2]).replace(a[2], a[3])
  • I tested it and it worked, because, as they said above, strings are immutable, so for the above code to work we have to put it inside a variable, and print this new variable.

  • 1

    In fact, that is not a solution to the problem. What you are doing is replacing the characters 'c' by’d' and’d' by 'c', but if the string has these repeated characters, it will not work. To check, just do a = "cdcd", instead of permuting characters 2 and 3, it will permute 0 and 1, as it is the first letters 'c' and’d' that JS finds in string.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.