Your looking for Boolean algebra. Below are the key formulas as well as a schematic diagram (drawing out the steps can help visualize). Wikipedia goes into detail will more rules such as Monotone laws and Nonmonotone laws
Basic Rules:
- BUF :
A=(A')'=AA=A+A = A+(BB')=A(B+B')
- NOT :
A'=((A')')'
- AND :
AB=((AB)')'=(A'+B')'
(AND: inverted output NAND or invented inputs NOR)
- OR :
A+B=((A+B)')'=(A'B')'
(OR: inverted output NOR or invented inputs NAND)
- XOR :
A^B=A'^B'=((A^B)')'=(A^B')'=AB'+A'B=(A+B)(AB)'=((A(AB)')'(B(AB)')')'
- XNOR :
(A^B)'=((A'^B')')'=(A^B)'=A^B'=AB+(A+B)'=((AB)'(A+B))'=((A+(A+B)')'+(B+(A+B)')')'
Other Common:
AB+CD = ((AB)'(CD)')'
(A+B)(C+D) = ((A+B)'+(C+D)')'

simulate this circuit – Schematic created using CircuitLab
Method to represent XOR as four NAND gates:
A^B = AB' + A'B // add forms of 0, BUF rule
= AA'+AB' + A'B+BB' // factor out A and B, algebra
= A(A'+B') + (A'+B')B // represent (A'+B') as C :: Reminder (A'+B')=(AB)'
= AC + CB // represent AC as X and CB as Y
= X + Y // substitute X+Y as (X'Y')', OR rule
= (X'Y')' // restore X and Y to original values
= ((AC)'(CB)')' // restore C as (AB)', equivalent to (A'+B')
= ((A(AB)')'((AB)'B)')'// DONE, XOR as 4 NAND gates, sharing the (AB)' line
Another method to do the same:
A^B = (A+B)(AB)' // represent (AB)' as C
= (A+B)C // Distribute C
= AC+BC // represent AC as X and BC as Y
= X+Y // substitute X+Y as (X'Y')', OR rule
= (X'Y')' // restore X and Y to original values
= ((AC)'(BC)')' // restore C as (AB)', equivalent to (A'+B')
= ((A(AB)')'(B(AB)')')'// DONE, XOR as 4 NAND gates, sharing the (AB)' line