The object does not have a 'replace' method

I'm trying to run this function, which captures all checked flag values ​​into a comma-separated string and converts "," to ", " so it reads better. The problem is that I get a weird error:

 $('.name_boxes').live('click', function() { var all_boxes = $('.name_boxes'); var all_boxes_values = [] for (var i = 0; i < all_boxes.length; i++) { if (all_boxes[i].checked) { all_boxes_values.push(all_boxes[i].value) } } var all_boxes_values_clean = all_boxes_values.replace(/,/g,", "); alert(all_boxes_values_clean); }); 

The console error says:

Uncaught TypeError: Object Aaron Ramsey, Aaron Renfree does not have a replace method.

I do not get a warning.

It's a little taller than me, can someone explain what I'm doing wrong?

+6
source share
2 answers

Although alert(some_array) prints a string representation of the array, the array itself is not a string. So it does not have .replace . alert forced to convert it to a string because only characters can be displayed in the warning field.

However, you can just join the custom delimiter. join is an array function:

 var all_boxes_values_clean = all_boxes_values.join(", "); 

As a side note, I recommend console.log over alert because it:

  • shows the actual object / array instead of the string representation (especially useful for objects instead of the useless [object Object] that you get with alert )
  • frees you from closing a popup every time
  • keeps track of other logs so you have the actual log of logs
+11
source

all_boxes_values is an array, not a string, and therefore it does not have a replace method.

Try

 var all_boxes_values_clean = all_boxes_values.join(", "); 

If you insist on doing regular expressions, first convert the array to a string: all_boxes_values.toString() .

+4
source

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


All Articles