简体   繁体   中英

How to remove unwanted character in HTML jQuery JavaScript

I am trying to remove these "," from my HTML. I have tried .replace(",", "") , .join() and other methods but to no success.

Here is what it looks like in the console and on my page, notice the commas: 在此输入图像描述

Here is my code:

        var featuresArray = jQuery(".Features").siblings().children("p").text().replace(",", "").split("\n");

        var boom =  featuresArray.map(function (item, index) {              
          return '<li>'+item+'</li>';
          });
        var features = boom;


        printWindow.document.write("<p class='product-attribute'>"+'Features: ' + '<ul class="product-attribute-details">' + features + "</ul></p>");

How can I remove these commas from my UL ?

The issue is because you're concatenating the array directly with the HTML string. As such, it will have toString() called on it. This is effectively doing .join(',') . This is why the commas appear between the li elements, as you can see in this basic example:

 var foo = ['a', 'b', 'c']; console.log(foo.toString()); 

To fix this, manually call join('') on the array as you concatenate it:

printWindow.document.write('<p class="product-attribute">Features: <ul class="product-attribute-details">' + features.join('') + '</ul></p>');

Note that I made the quotes consistent in the above line, and also removed the unnecessary concatenation you were doing in a couple of places

Use .join('') on the array before writing it into HTML.

Since arrays aren't strings, JS will call the default .toString() function of the array when concatenating it with a string, which causes the extra commas to appear in the HTML:

 var ary = [ 1, 2, 3 ]; document.write( ary ); document.write('<br>'); document.write( ary.join( '' ) ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM