我想缩短一些代码,这些代码有不同的方法来替换我设置的特定模式。基本上,此代码替换了我设置的HTML:<span class="combination">0000-AAAA-0000-BBBB</span>
function randomised(len) {
return Math.floor(Math.random() * len);
}
function randomiseStrings(str){
var alphSet = "abcdefghijklmnopqrstuvwxyz";
var numSet = "0123456789";
var alphNumSet = alphSet.concat(numSet);
// 1) Replace 0 with random number.
var str = str.replace(/0/g, function() {
return numSet[randomised(numSet.length)];
});
// 2) Replace A with random number or letter.
var str = str.replace(/A/g, function() {
return alphNumSet[randomised(alphNumSet.length)].toUpperCase();
});
// 3) Replace B with random letter.
var str = str.replace(/B/g, function() {
return alphSet[randomised(alphSet.length)].toUpperCase();
});
return str;
}
$('.combination').text(function(i,t){
return randomiseStrings(t);
});
所以你可以看到我有3个相同的脚本。但是我无法弄清楚如何去做。我的目标是能够更改这些值:str.replace(/[A]/g,
,a = alphSet/numSet/alphNumSet
以及添加:.toUpperCase();
的可能性。
问题我最终得到了如果我将其作为一个函数,我不知道如何返回这些值。对于任何建议或想法,我都会非常感激。
答案 0 :(得分:1)
您已经迈出了第一步并确定了代码的重复部分。您现在要做的就是使用这些部件作为参数创建一个函数。
function replaceWithRandom(text, regex, randomSet) {
return text.replace(regex, function() {
return randomSet[randomised(randomSet.length)].toUpperCase();
});
}
str = replaceWithRandom(str, /0/g, numSet);
str = replaceWithRandom(str, /A/g, alphSet);
str = replaceWithRandom(str, /B/g, alphNumSet);
numSet
仅包含字符串,因此调用toUpperCase
是多余的,但不会导致任何问题。
答案 1 :(得分:1)
这里有几个地方可以切脂肪。首先,我将继续并将所有alphSet大写,以便您不必调用toUpperCase()。 alphNumSet由2个字符串组成,您可以使用字符串连接来组合它们而不是concat函数。您正在寻找的功能只是要考虑您发送的呼叫之间的差异。
function randomised(len) {
return Math.floor(Math.random() * len);
}
function getRandom(str, regEx, set){
return str.replace(regEx, function() {
return set[randomised(set.length)];
});
}
function randomiseStrings(str){
var alphSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numSet = "0123456789";
var alphNumSet = alphSet + numSet;
str = getRandom(str, /0/g, numSet);
str = getRandom(str, /A/g, alphNumSet)
str = getRandom(str, /B/g, alphSet)
return str;
}
$('.combination').text(function(i,t){
return randomiseStrings(t);
});