Visualize a Recursive Acronym

APL (Dyalog Extended), 33 32 bytes

-1 byte thanks to Bubbler.

Anonymous infix lambda. Takes count as left argument and string as right argument.

{('\b',⊃¨⍵⊆⍨≠⍵)⎕R(1⌽')(',⍵)⍣⍺⊢⍵}

Try it online!

{} "dfn"; number is and text is :

⊢⍵ on the text:

⍣⍺ repeat given number of times

()⎕R() PCRE Replace:

  ')(',⍵ the text prefixed by ")("

  1⌽ cyclically rotated one step left (puts ")" at end)

  … with:

  ≠⍵ The mask of non-spaces in the text

  ⍵⊆⍨ characters runs in the text corresponding to runs of 1s in that

  ⊃¨ first character of each

'\b', prepend PCRE for word boundary


JavaScript (ES9),  88 85  82 bytes

Takes input as (string)(n).

s=>g=n=>n?s.replace(eval(`/\\b${s.match(/(?<=^| )./g).join``}/g`),`(${g(n-1)})`):s

Try it online!

Commented

s =>                       // s = string
  g = n =>                 // g is a recursive function taking the counter n
    n ?                    // if n is not equal to 0:
      s.replace(           //   replace in s:
        eval(              //     each word matching:
          `/\\b${          //       a word boundary followed by
            s.match(       //       the acronym which consists of
              /(?<=^| )./g //         the letters that are preceded by
                           //         either a space or nothing at all
            ).join``       //       joined together
          }/g`             //
        ),                 //     with:
        `(${               //     the result of
          g(n - 1)         //       a recursive call
        })`                //     surrounded with parentheses
      )                    //   end of replace()
    :                      // else:
      s                    //   end of recursion: just return s

05AB1E, 27 25 22 bytes

ðìÐ#€нJðìs" (ÿ )"Iи.:¦

Try it online!

To make sure we only match the acronym at the beginning of a word, we match an extra leading space. This results in extra spaces in the output, which is allowed.

ðì                      # prepend a space to the input
  Ð                     # triplicate
   #€нJ                 # acronymize (split on spaces, head of each, join)
       ðì               # prepend a space to the acronym
         s              # swap
          " (ÿ )"       # surround with parentheses
                 Iи     # repeat the following second-input times:
                   .:   #  replace the acronym with the parenthesized string
                     ¦  # remove the leading space