function translateWord( textarea, oldText, newText ) {
var ctpos = getCaretPosition( textarea );
var textStr = textarea.value;
var oldTextLen = oldText.split("").length;
var newTextLen = newText.split("").length;
var txtDiffLen = ( newTextLen - oldTextLen );
var escText = oldText.replace( /([()\[\]\\\/+*?.-])/g, "\\$1" );
var regExpr = new RegExp( "\\b"+escText+"\\b", 'gi' );
var diffStr = textStr.match( regExpr );
diffStr = ( diffStr ) ? diffStr.length : 1;
var newStr = textStr.replace( regExpr, newText );
ctpos = ( ctpos + ( txtDiffLen * diffStr ) );
textarea.value = newStr;
setCaretPosition( textarea, ctpos );
}
function getCaretPosition( textarea ) {
if ( textarea.selectionStart ) {
return textarea.selectionStart;
}
else if ( !document.selection ) {
return 0;
}
var c = "\001",
sel = document.selection.createRange(),
dul = sel.duplicate(),
len = 0;
dul.moveToElementText( textarea );
sel.text = c;
len = dul.text.indexOf( c );
sel.moveStart( 'character', -1 );
sel.text = "";
return len;
}
function setCaretPosition( textarea, pos ) {
if ( textarea.setSelectionRange ) {
textarea.focus();
textarea.setSelectionRange( pos, pos );
}
else if ( textarea.createTextRange ) {
var range = textarea.createTextRange();
range.collapse( true );
range.moveEnd( 'character', pos );
range.moveStart( 'character', pos );
range.select();
}
}
translateWord( document.getElementById('text-input'), 'wakarimasu', 'わかります' );
我知道这是一个老问题,但这段代码会帮助像我这样的菜鸟:) 来自其他答案的混合函数:)