bento
bento

Reputation: 5026

javascript .replace and jQuery .map

I'm trying to teach myself the basics of working with JSON, Arrays, and Strings, so I'm attempting to build a simple Regex search and highlight. My problem is that when I try to replace the query term with a string that includes a queryterm it doesn't seem to return it to the new array that's being constructed.

Here's my function:

function jqueryMap() {
    var searchterm = "item"; 
    var query = new RegExp("itEM", "i");  
    var foo = $.map(array, function(value,key){
        if (value.classname.search(query) != -1){ //0 = none
            value.classname.replace(query, "<div class='highlight'>"+searchterm+"</div>"); 
            return value; 
        }
    });

    $.each(foo, function(key,value) {
        $("body").append(key +" : "+value.classname+" <br>");             
    });
}

and the array that it's searching:

var array = [{
    "classname": "item",
    "content": "content1"},
{
    "classname": "item",
    "content": "content2"},
{
    "classname": "item",
    "content": "content1"},
{
    "classname": "im gonna say its item",
    "content": "content1"},
{
    "classname": "blam",
    "content": "content1"},
{
    "classname": "item",
    "content": "content1"},
{
    "classname": "item3",
    "content": "content1"}];

My question, is why, when I return 'value' is the replaced text not being included? Thanks.

Here's my jsfiddle: http://jsfiddle.net/bmcmahen/5HQga/9/

Upvotes: 0

Views: 1477

Answers (1)

Matthew Flaschen
Matthew Flaschen

Reputation: 284927

replace returns a modified version. It doesn't modify anything in place (JavaScript strings are immutable). So you want:

value.classname = value.classname.replace(query, "<div class='highlight'>"+searchterm+"</div>"); 

Also, a regular for loop would be more appropriate, since you're returning the same array element that came in:

for(var i = 0; i < array.length; i++)

Upvotes: 2

Related Questions