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?
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?
Share Improve this question edited Jun 22, 2015 at 6:48 Tushar 87.2k21 gold badges163 silver badges181 bronze badges asked Jun 19, 2015 at 15:06 skobaljicskobaljic 9,6341 gold badge28 silver badges52 bronze badges 9- 3 What have you tried yourself so far to solve the problem? Have you done any research? Do you have a problem in your current code? – Anonymous Commented Jun 19, 2015 at 15:09
- 4 I am boring, what's wrong with boring! – Alex K. Commented Jun 19, 2015 at 15:10
- 2 "but that sounds boring" - you might want to clarify how you judge excitement so we know where to pitch the answers... Or more seriously that method is the one I'd go for, it would work and for the example you've given wouldn't even suck that much. What about that method do you not like (I'm assuming "boring" was just facetious). – Chris Commented Jun 19, 2015 at 15:11
- You could use regex instead... – brso05 Commented Jun 19, 2015 at 15:11
- 1 Will all numbers be unique or could numbers be repeated? – brso05 Commented Jun 19, 2015 at 15:11
7 Answers
Reset to default 10You 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.
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>');
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(" ");
};
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
}
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
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))