Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch numbers in string

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?

like image 760
skobaljic Avatar asked Jun 19 '15 15:06

skobaljic


2 Answers

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

like image 193
Tushar Avatar answered Oct 11 '22 01:10

Tushar


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.

like image 21
Walter Chapilliquen - wZVanG Avatar answered Oct 11 '22 01:10

Walter Chapilliquen - wZVanG