寻找类似于microsoft office autocorrect的jquery textarea脚本

时间:2013-11-28 18:31:30

标签: javascript jquery textarea

我正在寻找类似于microsoft office autocorrect的jquery / javscript textarea脚本。使用Microsoft office,我可以编写像< =和get≤这样的东西。与那些相似:

 >= gives ≥  
 -> gives →   
 +- gives ±  
 (c) gives ©  
 (e) gives €

还有更多。是否存在一些为textarea输入字段模拟此功能的jquery / javascript脚本?

编辑:谢谢你的回答!

1 个答案:

答案 0 :(得分:2)

我最近使用jquery制作了类似于MS office auto的内容 以下是演示:http://jsfiddle.net/73sEv/6/

function autoCorrect(searchString, replaceString) {
    $("textarea").keyup(function(e) {
        // escape some regex chars
        var escapedString = searchString.replace( /([\\.*+?|()\[\]{}])/g, "\\$1" );
        // finds current cursor position
        var pos = $(this).prop("selectionStart");
        // this turns the textarea in a string
        var text = $(this).val();
        //only search for strings just typed
        var stringToSearch = text.substring(pos-searchString.length,pos);

        if (new RegExp(escapedString).test(stringToSearch) === true) {
            //if there is a match put the replaceString in the right place
            var newText = text.substring(0,pos-searchString.length) + replaceString + text.substring(pos);            
            $(this).val(newText);
            //adjust the cursor position to the new text
            var newpos = pos - searchString.length + replaceString.length;
            this.setSelectionRange(newpos,newpos);
        }
    });
}

您可以自定义您想要的方式。例如:

autoCorrect("=>", '⇒');
autoCorrect("->", "→");
autoCorrect("+-", "±");
autoCorrect("<=", "≤");
autoCorrect(">=", "≥");
autoCorrect("(c)", "©");
autoCorrect("(e)", "€");