0

I need to extract the longest possible result from my spintax. But I can not find a way to add in the non-spun text. My code is extracting the longest option when there is a choice available but it is ignoring the content outside of the spintax curly brackets.

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);

The loop I'm using to count up the longest options is only counting the spintax variations. So it is skipping "a", "of a sentence" and "spintax"

How would I add these so they are counted too?

Thanks in advance... and sorry for the messy code!

Steve Hall
  • 113
  • 1
  • 7

1 Answers1

1

A friend on Facebook answered this for me :) So for anybody that has the same questions here is his solution:

<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>
Steve Hall
  • 113
  • 1
  • 7