我想使用 jquery get 函数读取一个 html 文件,替换一些字符然后显示结果。我写了get函数,可以替换文本。表中有许多行。行内的所有数据显示为文本。行以空格结尾;所以我想替换每一行的" ;"字符。但是下面的代码只是替换了第一行的字符。如何替换所有行的所有" ;"字符?
$.ajax({
url: 'http://url',
type: 'GET',
success: function(data) {
var def = $(data).find('tbody#div.divWord').html();
$('#def').append('<p><b>' + word + '</b>:' + def + '</p>');
$("div").each(function() {
var text = $(this).text();
text = text.replace(" ;", "@");
$(this).text(text);
});
},
error: function(data) {
alert('error');
}
});
默认情况下
,替换函数仅匹配第一个结果。
如果要替换每个匹配项,则必须采用正则表达式并设置"全局标志":
text = text.replace(/ ;/g, "@");
或
text = text.replace(/s;/g, "@");
其中s
与空格字符匹配。
或
text = text.replace(new RegExp(" ;","g"),"@");
text = text.replace(" ;", "@"); -> text = text.replace(/ ;/g, "@");
在替换中使用正则表达式,以便可以指定全局 (g) 标志:
text = text.replace(/ ;/g, "@");