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?
也请尝试:
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"
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
我不能判断这是否无聊,但至少它不是分裂和循环:)
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>');
链接地址: http://www.djcxy.com/p/74958.html
上一篇: 将数字附加到以逗号分隔的列表中
下一篇: 在字符串中切换数字