How to draw a text from a span and trim the end of each span as well as separate each span with a comma, via JavaScript?

var a = $('#tegs_tagsinput').first().contents().filter(function() { return this.nodeType == 1; }).text().slice(0, -3); document.getElementById('content').innerHTML = a; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="tegs_tagsinput" style="display:none"> <span class="tag"><span>1&nbsp;&nbsp;</span><a href="#" title="Removing tag">x</a></span> <span class="tag"><span>2&nbsp;&nbsp;</span><a href="#" title="Removing tag">x</a></span> <span class="tag"><span>3&nbsp;&nbsp;</span><a href="#" title="Removing tag">x</a></span> </div> <div id="content"></div> 

With the help of slice , the last 3 characters were removed from the entire text, and how to remove 3 characters from each span and separate them from commas? so that in the end we get 1,2,3

    2 answers 2

    Select all the span with the tag class, take the text of the first span inside, clear the spaces:

     var a = []; $('#tegs_tagsinput .tag').each(function() { a.push($(this).find('span').eq(0).text().replace(/\s+/g, '')); }); document.getElementById('content').innerHTML = a.join(','); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="tegs_tagsinput" style="display:none"> <span class="tag"><span>1&nbsp;&nbsp;</span><a href="#" title="Removing tag">x</a></span> <span class="tag"><span>2&nbsp;&nbsp;</span><a href="#" title="Removing tag">x</a></span> <span class="tag"><span>3&nbsp;&nbsp;</span><a href="#" title="Removing tag">x</a></span> </div> <div id="content"></div> 

      This is how you can delete the last 2 characters of each span and get an array of data with which you can already work freely. If you only need to leave the first character, and there will be a lot of characters in the span, then you need to make other slice conditions, for example: slice(0, 1) .

       var string = [], i = 0; while(document.getElementsByClassName('tag')[i]) { string.push(document.getElementsByClassName('tag')[i].firstChild.textContent.slice(0, -2)); i++; } console.log(string); 
       <div id="tegs_tagsinput" style="display:none"> <span class="tag"><span>1&nbsp;&nbsp;</span><a href="#" title="Removing tag">x</a></span> <span class="tag"><span>2&nbsp;&nbsp;</span><a href="#" title="Removing tag">x</a></span> <span class="tag"><span>3&nbsp;&nbsp;</span><a href="#" title="Removing tag">x</a></span> </div> <div id="content"></div>