This question already has answers here:
Replace method doesn't work
                                
                                    (4个答案)
                                
                        
                                3年前关闭。
            
                    
我正在尝试查找字符串中每个出现的字符串,并将其替换为

<span class="blue_color_text">matched_string</span>


这就是我正在使用的(在其中一个问题中找到了它):

String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};


这是实际的实现:

function showResult(str)
{
if (str.length == 0)
{
return;
}

if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}

xmlhttp.onreadystatechange = function() {

var e = document.getElementById("res_ls");

if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
xmlhttp.responseText.replaceAll(search_string.value, "<span class=\"green\">"+search_string.value+"</span>");
e.innerHTML = xmlhttp.responseText;
e.removeAttribute("class");
}
}

xmlhttp.open("GET","ajax.php?s="+str, true);
xmlhttp.send();
}

String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};


实际上没有任何改变。知道为什么吗?

最佳答案

.replaceAll()返回修改后的字符串的新实例,它不会更改现有的字符串引用。因此,如果要引用修改后的字符串,则需要存储.replaceAll()返回的值

你需要使用

e.innerHTML = xmlhttp.responseText.replaceAll(search_string.value, "<span class=\"green\">"+search_string.value+"</span>");

关于javascript - replaceAll不会更改任何内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17937751/

10-12 13:01