1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

[GET] JS spintax spinner function

Discussion in 'HTML & JavaScript' started by Bot Solutions, Oct 28, 2015.

  1. Bot Solutions

    Bot Solutions Regular Member

    Joined:
    Aug 19, 2014
    Messages:
    219
    Likes Received:
    362
    Occupation:
    Bot maker
    Location:
    Hungary
    Home Page:
    So for my current project, I needed a spintax spinner.
    Since I was not able to find any working one, I thought I will share it.

    The ones I found are not able to handle multi-nested spintaxes. My code is.

    Squarebrackets and the pipe has special meaning (of course), also all Ł will be replaced with L.

    Code:
    String.prototype.replaceAt=function(index, character) {
        return this.substr(0, index) + character + this.substr(index+character.length);
    }
    
    
    
    function Spin(spintax) {
        spintax = spintax.replace(/Ł/g,"L");
        var points = [];
        for (var i = 0; i < spintax.length; i++) {
            var ch = spintax[i];
            if (ch == "{")
                points.push(i);
            else if (ch == "}") {
                var subSpintax = spintax.substring(points[points.length - 1], i + 1).split("|");
                var position = Math.floor(Math.random() * subSpintax.length);
                for (var j = 0; j < subSpintax.length; j++) {
                    if (j != position)
                        for (var l = 0; l < subSpintax[j].length; l++)
                            subSpintax[j] = subSpintax[j].replaceAt(l, "Ł");
                }
                subSpintax = subSpintax.join("{");
                spintax = spintax.replaceAt(points[points.length - 1], subSpintax);
                points.splice(points.length - 1, 1);
            }
        }
        return spintax.replace(/Ł|\{|\}/g,"");
    }
    
    var spintax = "Black{|hat{|world}}";
    alert(Spin(spintax));
    
    
     
    • Thanks Thanks x 1