There are following implementation methods:
In Firefox, Google Chrome, Safari, Opera: you can use window.getSelection() (refer to MDC)
In IE, you can use document.selection.createRange().text (refer to MSDN)
Note: The code that puts the two together: