Why doesn't javascript.replace work on this array key?

here I add the text of each '. cmsCategories' in item_array, but then .replace () will not work with item_array keys. How can i fix this? (after that I will write the new content back to the div). Any help would be awesome!

http://jsfiddle.net/QKHJJ/1/

JavaScript:

$(document).ready(function() { var item_array=new Array(); $("[class=' cmsCategories']").each(function(i, obj) { item_array.push(obj.innerHTML); }); item_array[0].replace("icon_dog", "<img src='img/icon_dog.png' alt='icon_dog' />"); item_array[0].replace("icon_cat", "<img src='img/icon_cat.png' alt='icon_cat' />"); alert(item_array[0]); }); 

HTML:

 <ul class="cmsSmartListResults"> <li> <div class=" cmsCategories">icon_cat, apple, icon_dog, pear, banana</div> <a href="" class=" cmsPageLink"></a> <div class=" cmsDescription"></div> <div class=" cmsFileSize"></div> <a class=" cmsMoreLink"></a> </li> <li> <div class=" cmsCategories">apple, icon_dog</div> <a href="" class=" cmsPageLink"></a> <div class=" cmsDescription"></div> <div class=" cmsFileSize"></div> <a class=" cmsMoreLink"></a> </li> <li> <div class=" cmsCategories">pear, banana</div> <a href="" class=" cmsPageLink"></a> <div class=" cmsDescription"></div> <div class=" cmsFileSize"></div> <a class=" cmsMoreLink"></a> </li> </ul> 
+4
source share
5 answers

1) The replacement function does not change the line you pass (the lines are immutable): it returns a new one.

Do:

 var newString = item_array[0].replace(... 

or

 item_array[0] = item_array[0].replace(... 

2) After this operation, you must again change the DOM with $('someselector').html(item_array[0]);


The complete code you need is something like

 $("[class=' cmsCategories']").each(function(i, obj) { var html = $(this).html(); html = html.replace ... $(this).html(html); }); 
+6
source

The replacement method does not change the original value. You will need to do something like:

 item_array[0] = item_array[0] .replace("icon_dog", "<img src='img/icon_dog.png' alt='icon_dog' />"); 
+3
source

You have to do

 item_array[0] = item_array[0].replace("icon_dog", "<img src='img/icon_dog.png' alt='icon_dog' />") 
+2
source

I think your replace statement is incorrect. Try it.

 item_array[0] = item_array[0].replace("icon_dog", "<img src='img/icon_dog.png' alt='icon_dog' />"); item_array[0] = item_array[0].replace("icon_cat", "<img src='img/icon_cat.png' alt='icon_cat' />"); 

jsFiddle

+2
source

Updated jsFiddle, you forgot array = array.replace.

http://jsfiddle.net/QKHJJ/3/

+1
source

Source: https://habr.com/ru/post/1435081/


All Articles