A
A
Alex2015-11-03 18:26:12
JavaScript
Alex, 2015-11-03 18:26:12

How to swap characters in a string?

Let's say I have some string var str = '9876';. And I need to swap characters based on their order. For example 1 and 3, result: var str = '9678';
How?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Ineshin, 2015-11-03
@Kozack

Well, like this: jsfiddle.net/sxzk9ooa

function sortMe (s) {
    var arr = s.split('');
    arr.sort(function (a, b) {
        return a > b; // тут любой ваш алгоритм сортировки
    });
    return arr.join('');
}

var newStr = sortMe('9876');
console.log(newStr); //6789

K
Konstantin Gromov, 2015-11-03
@Pathgk

function replaceChars(string, from, to) {
  if (string[from] != undefined && string[to] != undefined) {
    var newString = Array.prototype.slice.call(string);

    newString[from] = string[to];
    newString[to] = string[from];

    return newString.join("");
  } else {
    return string;
  }
}

replaceChars("qwerty", 2, 4); // "qwtrey"

I
Immortal_pony, 2015-11-03
@Immortal_pony

var resultStr = str[0]+str[3]+str[2]+str[1];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question