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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With