【问题标题】:jQuery Find / Replace in Lots of TextjQuery 在大量文本中查找/替换
【发布时间】:2012-05-22 15:35:07
【问题描述】:

我正在使用 jQuery,我需要为从文本文件“example.txt”中提取的文本创建一个查找/替换表单。

首先,这里是 HTML:

<div id="outbox" class="outbox">
<h3>Output</h3>
<div id="output"></div>
</div>
<div class="content">
<h3>Text File Location</h3>
<br />
<form id="prac" action="prac9.html">
    <input id="locator" type="text" value="example.txt" /> <br />
    <input id="btnlocate" value="Load" type="button" />
</form>
<br />
<h3>String Search</h3>
<form id="prac2" action="prac9.html">
    <div id='input'><input type='text' id='fancy-input'/> ...Start Typing</div> <br />

</form>
<br />
<h3>Find / Replace String</h3>
<form id="prac3" action="prac9.html">
    <input id="findtxt" type="text" value="" /> Find <br />
    <input id="replacetxt" type="text" value="" /> Replace<br />
    <input id="btnreplace" value="Find & Replace" type="button" />
</form>
</div>

这里是 jQuery/JS:

<script type="text/javascript">

$('#btnlocate').click(function () {

    $.get($('#locator').val(), function (data) {
        var lines = data.split("\n");
        $.each(lines, function (n, elem) {
            $('#output').append('<div>' + elem + '</div>');
            // text loaded and printed
        });
    });
});

/* SEARCH FUNCTION */

$(function () {       

    $('#fancy-input').keyup(function () {
        var regex;
        $('#output').highlightRegex();
        try { regex = new RegExp($(this).val(), 'ig') }
        catch (e) { $('#fancy-input').addClass('error') }

        if (typeof regex !== 'undefined') {
            $(this).removeClass('error');
            if ($(this).val() != '')
                $('#output').highlightRegex(regex);
        }
    })
});

 /* SEARCH FUNCTION FOR FIND REPLACE */
 $(function () {
    $('#findtxt').keyup(function () {
        var regex;
        $('#output').highlightRegex();
        try { regex = new RegExp($(this).val(), 'ig') }
        catch (e) { $('#findtxt').addClass('error') }

        if (typeof regex !== 'undefined') {
            $(this).removeClass('error');
            if ($(this).val() != '')
                $('#output').highlightRegex(regex);
        }
        })
    });

 /* regexp escaping function */

  RegExp.escape = function (str) {
      return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  };

    $('#btnreplace').click(function () {
        var needle = $('#findtxt').val();
        var newneedle = $('#replacetxt').val();
        var haystack = $('#output').text();
      //  var regex = new RegExp(needle, "g");
        haystack = haystack.replace(new RegExp(RegExp.escape(needle), "g"), newneedle);
        console.log(haystack);
    });

您可能已经注意到,如果相关的话,我使用了一个插件“jQuery Highlight Regex Plugin v0.1.1”。

http://pastebin.com/HmqWmKsy 是“example.txt”,如果这也相关的话。

我需要的只是一种简单的查找/替换方法,但网络上的所有东西都没有帮助我。

如果您需要更多信息,请告诉我。

【问题讨论】:

    标签: javascript jquery regex replace find


    【解决方案1】:

    使用replace 和正则表达式,您走在了正确的轨道上。您想添加“全局”标志 (g),并且您必须通过 new RegExp(string) 创建表达式,因为您的 needle 是一个字符串。例如:

    haystack = haystack.replace(new RegExp(needle, "g"), newNeedle); // BUT SEE BELOW
    

    上面的几乎有效,只是如果needle中有任何字符在正则表达式中是特殊的(*[]等),显然new RegExp将尝试解释它们。不幸的是,RegExp 没有转义字符串中所有正则表达式字符的标准方法,但您可以添加它:

    RegExp.escape = function(str) {
      return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
    };
    

    (来自Prototype,但我们可以直接复制它而不是实际使用整个库,它是 MIT 许可的。请务必注明您的来源。或者使用其他地方的 this version。)

    所以我们最终得到:

    haystack = haystack.replace(new RegExp(RegExp.escape(needle), "g"), newNeedle);
    

    这是一个完整的工作示例:Live copy | source

    HTML:

    <div>
      <label>Haystack:
        <br><textarea id="theHaystack" rows="5" cols="50">Haystack with test*value more than once test*value</textarea>
      </label>
    </div>
    <div>
      <label>Needle:
        <br><input type="text" id="theNeedle" value="test*value">
      </label>
    </div>
    <div>
      <label>New Needle:
        <br><input type="text" id="theNewNeedle" value="NEW TEXT">
      </label>
    </div>
    <div>
      <label>New haystack:
        <br><textarea readonly id="theNewHaystack" rows="5" cols="50"></textarea>
      </label>
    </div>
    <div>
      <button id="theButton">Replace</button>
    </div>
    

    JavaScript:

    RegExp.escape = function(str) {
      return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
    };
    jQuery(function($) {
    
      $("#theButton").click(function() {
        var haystack = $("#theHaystack").val(),
            needle   = $("#theNeedle").val(),
            newNeedle = $("#theNewNeedle").val(),
            newHaystack;
    
        if (!haystack || !needle) {
          display("Please fill in both haystack and needle");
          return;
        }
    
        newHaystack = haystack.replace(
          new RegExp(RegExp.escape(needle), "g"),
          newNeedle);
        $("#theNewHaystack").val(newHaystack);
      });
    
      function display(msg) {
        $("<p>").html(msg).appendTo(document.body);
      }
    });
    

    【讨论】:

    • 感谢您的快速回复。输出的干草堆没有变化,我错过了什么?
    • @Henryccc: replace 不会原地改变字符串,它返回改变的字符串;请参阅上面我将结果分配回haystackhaystack = haystack.replace(...); 而不仅仅是haystack.replace(...);。你错过了那部分吗?
    • 抱歉,再次重新更新,但即使我将其设置为newhaystack = haystack.replace(...),它仍然没有更新的干草堆。我完全不明白哈哈。
    • @Henryccc:我没有立即发现您添加的新代码有问题。我在答案中添加了full working example
    • 谢谢,我意识到这是导致问题的代码的不同部分!非常感谢!
    猜你喜欢
    • 2011-03-05
    • 2012-05-31
    • 2021-10-25
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多