Switch numbers in string

478 views Asked by At

I have a string with space-separated unique numbers as following:

"2 4 13 14 28 33"

Need a quick and efficient way to switch a pair of them in form:

switchNumbers(2, 28)
// result: "28 4 13 14 2 33"

I could split the string and search for values, but that sounds boring. Any better idea?

7

There are 7 answers

2
Walter Chapilliquen - wZVanG On BEST ANSWER

Try also:

var numbers = "2 4 13 14 28 33";

function switchNum(from, to){
  return numbers.replace(/\d+/g, function(num){
    return num == from ? to : num == to ? from :  num
  })
}

alert(switchNum(2, 28)) //result: "28 4 13 14 2 33"

Note: Do not use switch as function name, switch is a statement for JavaScript.

1
Sachin Gadagi On
var str = "2 4 13 14 28 33";
switchNumbers(2,28);  // call
function switchNumbers(a,b)
{


var split_ = str.split(" ");

var index_of_1 = split_.indexOf(a+"");
var index_of_2 =  split_.indexOf(b+"")

temp =  split_[index_of_1];
split_[index_of_1] = split_[index_of_2] ;
split_[index_of_2] = temp ;


split_.toString(" "); // Answer
}
0
Jason Cust On

I can't judge if this is boring or not but at least it's not splitting and looping :)

function switchNumbers(str, x, y) {
  var regexp = new RegExp('\\b(' + x + '|' + y + ')\\b', 'g'); // /\b(x|y)\b/g
  return str.replace(regexp, function(match) { return match == x ? y : x; });
}

var s = "2 4 13 14 28 33";

document.write('<pre>' + switchNumbers(s, 2, 28) + '</pre>');

0
Tushar On

You can take advantage of array functions instead of strings.

See comments inline in the code:

var str = "2 4 13 14 28 33";

// Don't use `switch` as name
function switchNumbers(a, b) {
    var arr = str.split(' ');
    // Convert string to array

    // Get the index of both the elements
    var firstIndex = arr.indexOf(a.toString());
    var secondIndex = arr.indexOf(b.toString());


    // Change the position of both elements
    arr[firstIndex] = b;
    arr[secondIndex] = a;


    // Return swapped string
    return arr.join(' ');
}


alert(switchNumbers(2, 28));

DEMO

0
Tim On

I'm sure this isn't the best way.. but it works..

var swapnums = function(x,first,second) {
    var y = x.split(" ");
    var locOfFirst = y.indexOf(first.toString());
    var locOfSecond = y.indexOf(second.toString());
    y[locOfFirst] = second.toString();
    y[locOfSecond] = first.toString();
    return y.join(" ");
};
2
Rose R. On

I think your best solution might be to use JavaScript's native replace method for strings.

W3Schools has a nice low-down on it here. It should do exactly what you want, but may replace ALL the numbers you specify, so be sure to say something like var replacement = str.replace("2 ", "28 ");

EDIT: Pointed out a good flaw with this. Instead you could try:

EDIT2: Opps, had some flaws in the original code. Tested and works fine! :)

    function replaceNumbers(x1, x2, str) {
        var strMod = " " + str + " "
        var x1Mod = " " + x1 + " "
        var x2Mod = " " + x2 + " "
        
        // Want to replace "farthest" first to ensure correct replacement.
        if (str.indexOf(x1Mod) > str.indexOf(x2Mod)) {
            strMod = strMod.replace(x1Mod, x2Mod)
            strMod = strMod.replace(x2Mod, x1Mod)
        } else {
            strMod = strMod.replace(x2Mod, x1Mod)
            strMod = strMod.replace(x1Mod, x2Mod)
        }
        
        return strMod.slice(1, strMod.length - 1)
    }

   var numbers = "2 4 13 14 28 33";
   alert(replaceNumbers(2, 33, numbers))

0
Demonia On

Something like that should work.

var str= "2 4 13 14 28 33";
function switchNumbers(a, b) {
    var arr = str.split(" ");
    var first= arr.indexOf(a), second = arr.indexOf(b);
    arr[first] = arr.splice(second, 1, arr[first])[0];
    return arr.join(" ");
}

Jsfiddle demo