Search code examples
javascriptstring-length

how can i print in javascript a string in parts


I have an exercise from my university that i have a string let's say i have that: "hello" and i want to print it like that:

hhehelhellhello (h he hel hell hello).

the thing that i stack is that they want to do it without loop!

Anyone can help me? :/

    <!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
var strin = "hello" 
for (i = 0; i < strin.length; i++) {
   document.write(strin.slice(0,i+1))
}


</script>

</body>
</html>

Solution

  • Use recursion. Code:

    function r (s, i) {
     if (i == undefined) i = 0;
     if (i == s.length) return "";
     return s.slice(0, i + 1) + r(s, i + 1);
    }
    
    r("hello"); // hhehelhellhello