How can I reduce this code? (JavaScript)

1

I am trying to generate links automatically for one chapter to another (in different .html) I got this code but I think it is too long as it could redurct / improve it

<html>

<body>
    <div id="caps">
    </div>
<script>
    let url = "capitulo-10.html" //window.location;
    let str = url.toString();
    let numcap = str.slice(-7, -5);
    let res = str.slice(0, -8);

    let ant = parseInt(numcap) - 1;
    let sig = parseInt(numcap) + 1;

    let caps = document.querySelector("#caps");

    if (ant < 10) {
        caps.innerHTML += "<a href='" + res + "-0" + ant + ".html'>Capitulo Anterior</a><br>";
    } else {
        caps.innerHTML += "<a href='" + res + "-" + ant + ".html'>Capitulo Anterior</a><br>";
    }

    if (sig < 10) {
        caps.innerHTML += "<a href='" + res + "-0" + sig + ".html'>Capitulo Siguiente</a><br>";
    } else {
        caps.innerHTML += "<a href='" + res + "-" + sig + ".html'>Capitulo Siguiente</a><br>";
    }
</script>
</body>

</html>
    
asked by Leonel Salcedo Retamozo 26.06.2018 в 10:52
source

1 answer

4

I can think of the following: Use string templates and the ternary operator.

In addition, +'<numero entero como texto>' is almost the same as parseInt('<numero entero como texto>')

let url = "capitulo-10.html" //window.location;
let str = url.toString();
let numcap = str.slice(-7, -5);
let res = str.slice(0, -8);

let ant = +numcap - 1;
let sig = +numcap + 1;

ant = ant < 10 ? '0' + ant : ant;
sig = sig < 10 ? '0' + sig : sig;

let caps = document.querySelector("#caps");
caps.innerHTML += '<a href="${res}-${ant}.html">Capitulo Anterior</a><br>';
caps.innerHTML += '<a href="${res}-${sig}.html">Capitulo Siguiente</a><br>';
    
answered by 26.06.2018 / 11:15
source