1

I'm trying to find every occurrence of a string within a string, and replace it with

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

This is what I'm using (found it here in one of the questions):

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

Here's the actual implemention:

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);
};

Nothing is actually changing. Any idea why?

elad.chen
  • 2,375
  • 5
  • 25
  • 37

3 Answers3

4

.replaceAll() returns a new instance of the modified string, it does not change the existing string reference. So if you want to refer to the modified string then you need to store the value returned by .replaceAll()

you need to use

e.innerHTML = xmlhttp.responseText.replaceAll(search_string.value, "<span class=\"green\">"+search_string.value+"</span>");
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • coding with a fever is off the table permanently :) Thanks & Sorry for the rookie question. I really am sick though ;p – elad.chen Jul 30 '13 at 03:26
0

Strings in JavaScript are immutable, so replaceAll doesn't change the string itself, but returns a new string instead:

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

You need to assign the return value of replaceAll to the original string:

xmlhttp.responseText = xmlhttp.responseText.replaceAll(search_string.value, "<span class=\"green\">"+search_string.value+"</span>");
Ilmo Euro
  • 4,925
  • 1
  • 27
  • 29
0

Try using J-Query:

$('
//Code to find strings
').replaceWith('<span class="blue_color_text">matched_string</span>');
iCoder
  • 1