Skip to main content
added a commented version
Source Link
Arnauld
  • 197.7k
  • 20
  • 179
  • 650

JavaScript (ES6), 62 bytes

Expects (string, substring, n).

(s,q,n)=>(a=s.split(q))[n]+1?a.map(s=>a[++n]+1?s+q:s).join``:s

Try it online!

Commented

(s, q, n) => (   // s = string, q = substring, n = integer
  a = s.split(q) // split s on q and save the result in a[]
                 // if q appears x times, we get x + 1 entries
                 // some of these entries may be empty strings (falsy)
                 // so we do '+ 1' to distinguish between empty and undefined
)[n] + 1 ?       // if a[n] is defined:
  a.map(s =>     //   for each entry s in a[]:
    a[++n] + 1 ? //     increment n; if a[n] is still defined:
      s + q      //       append q to s
    :            //     else:
      s          //       leave s unchanged
  ).join``       //   end of map(); join everything back together
:                // else:
  s              //   return s unchanged

JavaScript (ES6), 62 bytes

Expects (string, substring, n).

(s,q,n)=>(a=s.split(q))[n]+1?a.map(s=>a[++n]+1?s+q:s).join``:s

Try it online!

JavaScript (ES6), 62 bytes

Expects (string, substring, n).

(s,q,n)=>(a=s.split(q))[n]+1?a.map(s=>a[++n]+1?s+q:s).join``:s

Try it online!

Commented

(s, q, n) => (   // s = string, q = substring, n = integer
  a = s.split(q) // split s on q and save the result in a[]
                 // if q appears x times, we get x + 1 entries
                 // some of these entries may be empty strings (falsy)
                 // so we do '+ 1' to distinguish between empty and undefined
)[n] + 1 ?       // if a[n] is defined:
  a.map(s =>     //   for each entry s in a[]:
    a[++n] + 1 ? //     increment n; if a[n] is still defined:
      s + q      //       append q to s
    :            //     else:
      s          //       leave s unchanged
  ).join``       //   end of map(); join everything back together
:                // else:
  s              //   return s unchanged
Source Link
Arnauld
  • 197.7k
  • 20
  • 179
  • 650

JavaScript (ES6), 62 bytes

Expects (string, substring, n).

(s,q,n)=>(a=s.split(q))[n]+1?a.map(s=>a[++n]+1?s+q:s).join``:s

Try it online!