的很多,我使用jQuery更換,我需要創建一個查找/對於從一個文本文件「example.txt中」拉文本替換形式。jQuery的查找/文本
首先,這裏是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的亮點正則表達式插件V0。 1.1「如果這是相關的。
http://pastebin.com/HmqWmKsy是 「將example.txt」 如果這也是有關。
我需要的就是這樣的查找/替換,但所有在網絡上的東西還沒有幫我的一個簡單的方法。
如果你需要的信息了,讓我知道吧。
感謝您的快速回復。 輸出的乾草堆沒有變化,我錯過了什麼? – henrycjc
@Henryccc:'replace'不會原地改變字符串,它*返回*改變的字符串;見上面我將結果分配給'haystack':'haystack = haystack.replace(...);'不僅僅是'haystack.replace(...);'。你錯過了那部分? –
對不起,再次重新發布,但即使我將它設置爲'newhaystack = haystack.replace(...)',它仍然沒有更新的乾草堆。我不完全明白哈哈。 – henrycjc