我需要从Spintax中提取最长的结果。但是我找不到添加非旋转文本的方法。当有选择可用时,我的代码将提取最长的选项,但它忽略了spintax大括号之外的内容。
var totalcount = 0;
var text = "{This is|Here} a {sample|demo} of a sentence {made with|created using} spintax";
var longtext = "";
var matches, options, random;
var regEx = new RegExp(/{([^{}]+?)}/);
while((matches = regEx.exec(text)) !== null) {
options = matches[1].split("|");
var long1 = matches[1].split("|");
var longest = long1[0];
var strcount = 0;
for (i = 0; i < long1.length; i++) {
if (long1[i].length > longest.length) {
longest = long1[i];
}
strcount = longest.length;
}
totalcount = totalcount + strcount;
longtext = longtext + ' ' + longest;
random = Math.floor(Math.random() * options.length);
text = text.replace(matches[0], options[random]);
}
document.write('Random spin:<br>'+text+'<br><br>');
document.write('Longest spin ('+strcount+' chars):<br>'+longtext);
我用来计算最长选项的循环仅计算了spintax的变化。因此它跳过了“ a”,“ of a句子”和“ spintax”
我该如何添加它们,使它们也算在内?
预先感谢...,对于代码混乱,我们深表歉意!
答案 0 :(得分:0)
Facebook上的一位朋友为我回答了这个问题:)因此,对于任何有相同问题的人,他的解决方案都是:
<script>
var matches, options, random;
var spintaxString = "{London|Birmingham|Ely} is a {nice|wonderful|fabulous} place with some great {cafes | bars | restaurants}";
var longestString = spintaxString;
var regEx = new RegExp(/{([^{}]+?)}/);
while((matches = regEx.exec(spintaxString)) !== null) {
options = matches[1].split("|");
random = Math.floor(Math.random() * options.length);
var longest = options[0];
for (i = 0; i < options.length; i++) {
if (options[i].length > longest.length) {
longest = options[i];
}
}
longestString = longestString.replace(matches[0], longest);
spintaxString = spintaxString.replace(matches[0], options[random]);
}
document.write('Random: '+spintaxString+' ('+spintaxString.length+' chars)<br>');
document.write('Longest: '+longestString+' ('+longestString.length+' chars)<br>');
</script>