0

我正在使用 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”,如果这也相关的话。

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

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

4

1 回答 1

5

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

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 许可的。一定要在你的源代码中注明属性。或者从其他地方使用这个版本。)

所以我们最终得到:

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

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

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);
  }
});
于 2012-05-15T06:49:42.767 回答