我想在'#area'中将'text1'的多次出现替换为'text2',这是我的代码可以正常工作:
var replaced = $('#area').html().replace(/text1/g, 'text2');
$('#area').html(replaced);
但是想象一下'text1'是输入框的值,所以:
var search = $('#blah').val();
var replaced = $('#area').html().replace(/search/g, 'text2'); <--- HERE IS THE PROBLEM
$('#area').html(replaced);
正如您在第二行中看到的,我做了/search/g
但是它无法正常工作,我应该如何将search
值放在那里?
答案 0 :(得分:1)
如果search
是变量,则需要使用动态正则表达式(RegExp)
if (!RegExp.escape) {
RegExp.escape = function (s) {
return value.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")
};
}
//then later in your method
var search = $('#blah').val();
var regex = new RegExp(RegExp.escape(search), 'gi');
var replaced = $('#area').html().replace(regex, 'text2');
$('#area').html(replaced);
答案 1 :(得分:1)
甚至更简单:
var search = $('#blah').val();
var re = new RegExp(search, 'g');
str = str.replace(re, '');
答案 2 :(得分:0)
HTML:
Replace String:
<input type="text" id="blah" />
<br/>Text:
<input type="text" id="area" />
<br/>
<button onclick="myReplace()">Replace</button>
JS:
function myReplace() {
var search = $('#blah').val();
var regex = new RegExp(search, 'g');
var replaced = $('#area').val().replace(regex, 'text2');
$('#area').val(replaced);
}