查找和替换文本区域

Posted

技术标签:

【中文标题】查找和替换文本区域【英文标题】:Find and Replace for an Textarea 【发布时间】:2011-12-08 12:40:13 【问题描述】:

有没有人知道如何制作一个查找和替换的东西,当你点击下一步时,它会带你到下一个找到的项目?

编辑:

对于文本区域。我想要一个可以将查找和替换添加到 Textarea 的 javascript 代码。我不想只是使用。

搜索()

或替换()。

目前我正在尝试这个:

function allIndexes() 
var indices = new Array();
var index = 0;
var i = 0;
while(index = $('#text').val().indexOf($('#search').val(), index) > 0) 
indices[i] = index;
i++;

return indices;

但这根本不起作用。

【问题讨论】:

【参考方案1】:

我更新了我之前的答案,并根据我之前的帖子概述的方向完成了搜索和替换功能。我在 Chrome 14、IE8 和 Firefox 3.6 中对此进行了测试。

查找:将选择搜索词的下一个实例。

查找/替换:将替换下一次出现的搜索字符串并选择替换

全部替换:将替换所有出现并选择最后被替换的文本

希望这是现在,您正在寻找的东西。你绝对应该可以从这里开始设计这个样式或者制作一个合适的类......

<script src="jquery.js" type="text/javascript"></script>    

<textarea id="txtArea" style="width: 300px; height:100px">
    This is a test. A test, i say. The word TEST is mentioned three times.
</textarea>

<p>
    <label for="termSearch">Search</label>
    <input type="text" id="termSearch" name="termSearch" value="test" /><br/>
    <label for="termReplace">Replace</label>
    <input type="text" id="termReplace" name="termReplace" value="solution" /><br/>
    <label for="caseSensitive">Case Sensitive</label>
    <input type="checkbox" name="caseSensitive" id="caseSensitive" /><br/>
    <a href="#" onclick="SAR.find(); return false;" id="find">FIND</a><br/>
    <a href="#" onclick="SAR.findAndReplace(); return false;" id="findAndReplace">FIND/REPLACE</a><br/>
    <a href="#" onclick="SAR.replaceAll(); return false;" id="replaceAll">REPLACE ALL</a><br/>
</p>

<script type="text/javascript">
    var SAR = ;

    SAR.find = function()
        // collect variables
        var txt = $("#txtArea").val();
        var strSearchTerm = $("#termSearch").val();
        var isCaseSensitive = ($("#caseSensitive").attr('checked') == 'checked') ? true : false;

        // make text lowercase if search is supposed to be case insensitive
        if(isCaseSensitive == false)
            txt = txt.toLowerCase();
            strSearchTerm = strSearchTerm.toLowerCase();
        

        // find next index of searchterm, starting from current cursor position
        var cursorPos = ($("#txtArea").getCursorPosEnd());
        var termPos = txt.indexOf(strSearchTerm, cursorPos);

        // if found, select it
        if(termPos != -1)
            $("#txtArea").selectRange(termPos, termPos+strSearchTerm.length);
        else
            // not found from cursor pos, so start from beginning
            termPos = txt.indexOf(strSearchTerm);
            if(termPos != -1)
                $("#txtArea").selectRange(termPos, termPos+strSearchTerm.length);
            else
                alert("not found");
            
        
    ;

    SAR.findAndReplace = function()
        // collect variables
        var origTxt = $("#txtArea").val(); // needed for text replacement
        var txt = $("#txtArea").val(); // duplicate needed for case insensitive search
        var strSearchTerm = $("#termSearch").val();
        var strReplaceWith = $("#termReplace").val();
        var isCaseSensitive = ($("#caseSensitive").attr('checked') == 'checked') ? true : false;
        var termPos;

        // make text lowercase if search is supposed to be case insensitive
        if(isCaseSensitive == false)
            txt = txt.toLowerCase();
            strSearchTerm = strSearchTerm.toLowerCase();
        

        // find next index of searchterm, starting from current cursor position
        var cursorPos = ($("#txtArea").getCursorPosEnd());
        var termPos = txt.indexOf(strSearchTerm, cursorPos);
        var newText = '';

        // if found, replace it, then select it
        if(termPos != -1)
            newText = origTxt.substring(0, termPos) + strReplaceWith + origTxt.substring(termPos+strSearchTerm.length, origTxt.length)
            $("#txtArea").val(newText);
            $("#txtArea").selectRange(termPos, termPos+strReplaceWith.length);
        else
            // not found from cursor pos, so start from beginning
            termPos = txt.indexOf(strSearchTerm);
            if(termPos != -1)
                newText = origTxt.substring(0, termPos) + strReplaceWith + origTxt.substring(termPos+strSearchTerm.length, origTxt.length)
                $("#txtArea").val(newText);
                $("#txtArea").selectRange(termPos, termPos+strReplaceWith.length);
            else
                alert("not found");
            
        
    ;

    SAR.replaceAll = function()
        // collect variables
        var origTxt = $("#txtArea").val(); // needed for text replacement
        var txt = $("#txtArea").val(); // duplicate needed for case insensitive search
        var strSearchTerm = $("#termSearch").val();
        var strReplaceWith = $("#termReplace").val();
        var isCaseSensitive = ($("#caseSensitive").attr('checked') == 'checked') ? true : false;

        // make text lowercase if search is supposed to be case insensitive
        if(isCaseSensitive == false)
            txt = txt.toLowerCase();
            strSearchTerm = strSearchTerm.toLowerCase();
        

        // find all occurances of search string
        var matches = [];
        var pos = txt.indexOf(strSearchTerm);
        while(pos > -1) 
            matches.push(pos);
            pos = txt.indexOf(strSearchTerm, pos+1);
        

        for (var match in matches)
            SAR.findAndReplace();
        
    ;


    /* TWO UTILITY FUNCTIONS YOU WILL NEED */
    $.fn.selectRange = function(start, end) 
        return this.each(function() 
            if(this.setSelectionRange) 
                this.focus();
                this.setSelectionRange(start, end);
             else if(this.createTextRange) 
                var range = this.createTextRange();
                range.collapse(true);
                range.moveEnd('character', end);
                range.moveStart('character', start);
                range.select();
            
        );
    ;

    $.fn.getCursorPosEnd = function() 
        var pos = 0;
        var input = this.get(0);
        // IE Support
        if (document.selection) 
            input.focus();
            var sel = document.selection.createRange();
            pos = sel.text.length;
        
        // Firefox support
        else if (input.selectionStart || input.selectionStart == '0')
            pos = input.selectionEnd;
        return pos;
    ;  
</script>

【讨论】:

没有搜索框吗?我不明白。 这也不是我想要的,但这是为了尝试。 :) 由于您的代码看起来很棒,您会得到最佳答案。你负担得起。 我更新了我之前的粗略方向,现在这是一个通过 javascript 在文本区域上搜索和替换功能的完整示例。让我知道这是否更有用。 嗨@Jens Fischer,我知道这是一篇旧帖子,但如果你看到这个,我会问:你能在这个脚本中添加一个保存功能吗,我的意思是 保存更改,谢谢,我希望你看到这个..【参考方案2】:

javascript---------------------------------

        function dog(id)
        
            return document.getElementById(id);
        
        function find()
        
            var a=dog("txtf").value;
            var b=dog("ta").value;
            var c="";
            for(var i=0;i<b.length;i++)
            
                var d=b.substr(i,a.length)
                if (d.indexOf(a) > -1)          
                    c=c +" " + (d.indexOf(a)+i);
            
            if (c!="")
            
                alert(c);
            
            else
            
                alert("not find");
            
        
        function replace()
        
            var a=dog("txtf").value;
            var b=dog("ta").value;
            var c="";
            for(var i=0;i<b.length;i++)
            
                var d=b.substr(i,a.length)
                if (d.indexOf(a) > -1)      
                
                    c=c + dog("txtr").value;
                    i=i+a.length-1;
                
                else
                    c=c + b.charAt(i);
            
            dog("ta").value=c;
        

html ---------------------------------------------- --

    <input type="text" id="txtf" value="this" style="width:427px"/>
    <input type="button" value="Find" style="width:70px" onclick="find()" /> </br>
    <input type="text" id="txtr" value="it" style="width:427px"/>

    <input type="button" value="Replace" style="width:70px" onclick="replace()"/> </br>
    <textarea id="ta" style="width:500px;height:500px">

这是一个用于测试查找和替换功能的文本区域 这是一个用 html 编程语言查找和替换的项目

【讨论】:

【参考方案3】:

//滚动有一些错误,所以下面是在chrome中正常工作的更正。

 //Complete code 

var SAR = ;

            SAR.find = function () 
                debugger;
                var parola_cercata = $("#text_box_1").val(); // the searched word
                // make text lowercase if search is supposed to be case insensitive
                var txt = $('#remarks').val().toLowerCase();
                parola_cercata = parola_cercata.toLowerCase();

                var posi = jQuery('#remarks').getCursorPosEnd(); // take the position of the word in the text

                var termPos = txt.indexOf(parola_cercata, posi);

                if (termPos !== -1) 
                    debugger;
                    var target = document.getElementById("remarks");
                    var parola_cercata2 = $("#text_box_1").val();
                    // select the textarea and the word
                    if (target.setSelectionRange) 

                        if ('selectionStart' in target) 
                            target.selectionStart = termPos;
                            target.selectionEnd = termPos;
                            this.selectionStart = this.selectionEnd = target.value.indexOf(parola_cercata2);
                            target.blur();
                            target.focus();
                            target.setSelectionRange(termPos, termPos + parola_cercata.length);
                        
                     else 
                        var r = target.createTextRange();
                        r.collapse(true);
                        r.moveEnd('character', termPos + parola_cercata);
                        r.moveStart('character', termPos);
                        r.select();
                    
                 else 
                    // not found from cursor pos, so start from beginning
                    termPos = txt.indexOf(parola_cercata);
                    if (termPos !== -1) 
                        var target = document.getElementById("remarks");
                        var parola_cercata2 = $("#text_box_1").val();
                        // select the textarea and the word
                        if (target.setSelectionRange) 

                            if ('selectionStart' in target) 
                                target.selectionStart = termPos;
                                target.selectionEnd = termPos;
                                this.selectionStart = this.selectionEnd = target.value.indexOf(parola_cercata2);
                                target.blur();
                                target.focus();
                                target.setSelectionRange(termPos, termPos + parola_cercata.length);
                            
                         else 
                            var r = target.createTextRange();
                            r.collapse(true);
                            r.moveEnd('character', termPos + parola_cercata);
                            r.moveStart('character', termPos);
                            r.select();
                        
                     else 
                        alert("not found");
                    
                
            ;


            $.fn.getCursorPosEnd = function () 
                var pos = 0;
                var input = this.get(0);
                // IE Support
                if (document.selection) 
                    input.focus();
                    var sel = document.selection.createRange();
                    pos = sel.text.length;
                
                // Firefox support
                else if (input.selectionStart || input.selectionStart === '0')
                    pos = input.selectionEnd;
                return pos;
            ;
        </script> 

【讨论】:

【参考方案4】:

这个答案是那些寻找更完整和完善版本的Jens Fischer's solution 的人,该版本具有附加功能,例如查找上一个、查找下一个、使用正则表达式查找和替换、撤消和重做。

这里是 GitHub 项目的链接:https://github.com/AlienKevin/SmartTextarea

【讨论】:

以上是关于查找和替换文本区域的主要内容,如果未能解决你的问题,请参考以下文章

如何查找文本区域中的文本是不是换行为多行?

如何在android中以编程方式查找TextView的文本区域(高度/宽度)

查找并替换 textarea 中的所有匹配字符串

用空格替换文本区域中的逗号、破折号和输入键

Chrome 扩展替换当前文本区域中的单词

如何通过跳过换行符将文本区域内容替换为“*”