Answer the question
In order to leave comments, you need to log in
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
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
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"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question