Determine the best text color for a given background color

What is the best way to determine the best color for a text that will have good contrast and will be pleasing to the eyes (i.e. it can be either white, any shade of grey or black) with the help of JavaScript? The colors are denoted in hexadecimal.