我正在使用 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”,如果这也相关的话。
我所需要的只是一种简单的查找/替换方法,但网络上的所有东西还没有帮助我。
如果您需要更多信息,请告诉我。