The visual editor is an TinyMCE implementation. The first way to repace a selected text, is to write a plugin for the TinyMCE.
If you do not want to write a plugin, use the tinyMCE
object:
add_action( 'admin_footer', 'tinyNagging' );
function tinyNagging() {
echo '
<script type="text/javascript">
jQuery(document).ready(
function() {
window.setInterval(
function(){
var selectedText = tinyMCE.activeEditor.selection.getContent( {format : "text"} );
if ( selectedText != "" )
tinyMCE.activeEditor.selection.setContent( "FooBar" );
},
1000
);
}
);
</script>
';
}
This script checks every second if a text is selected and replace it with 'FooBar'.
Get the selected text with tinyMCE.activeEditor.selection.getContent( {format : 'text'} );
for plain text or {format : 'html'}
for the html markup.
Set the new content with tinyMCE.activeEditor.selection.setContent( [YourNewContent] );
See the TinyMCE manpages