Can you add a check for range.isCollapsed() and if so do the modification of the anchor href. The else branch should have the formatText line.