This is called partial correlation, basically it, as Wikipedia notices,
measures the degree of association between two random variables, with
the effect of a set of controlling random variables removed
Having correlation coefficients of three variables $X$, $Y$ and $Z$ we can correct correlation $\rho_{XY}$ by controlling correlations of $X$ and $Y$ with $Z$:
$$ \rho_{XY \cdot Z } = \frac{\rho_{XY} - \rho_{XZ}\rho_{ZY}} {\sqrt{(1-\rho_{XZ}^2) (1-\rho_{ZY}^2)}} $$
This is related to multiple linear regression. To test the hypothesis about partial correlation you use $t$-statistic in similar fashion as with regular correlation but with $N-3$ degrees of freedom. The same formula can be used for Pearson's or Spearman's correlation coefficients (for more see Altman, 1991 or Revelle, n.d.).
There are multiple R functions and libraries that enable you to calculate partial correlations like pcor, ggm or psych.
Altman, D.G. (1991). Practical Statistics for Medical Research. Chapman and Hall, pp. 288-299.
Revelle, W. (n.d.). Multiple Correlation and Multiple Regression In: An introduction to psychometric theory with applications in R.