Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery implode/join strings (elements) with a custom character (hyphen)

Tags:

jquery

i have a selection of (2) elements, selected by this:

$(this).parents("tr:first").children("td").children("span");

when i do this:

$(this).parents("tr:first").children("td").children("span").text();

the texts in the spans (say a and b) are concatenated together (to ab), and thats almost what i want

But now i want to concatenate them by inserting a hyphen (-) in between (to a - b) I've tried this, but that doesn't work:

$(this).parents("tr:first").children("td").children("span").join(" - ");
like image 467
Michel Avatar asked Feb 25 '11 11:02

Michel


4 Answers

Use $.map:

$.map(
  $(this).parents("tr:first").children("td").children("span"), 
  function(element) {
      return $(element).text()
  })
  .join(" - ");
like image 113
aavezel Avatar answered Nov 20 '22 23:11

aavezel


$(this)
    .parents('tr:first')
    .children('td')
    .children('span')
    .append('-') // append hyphen to each span
    .text();
like image 32
Gajus Avatar answered Nov 20 '22 23:11

Gajus


Perhaps something like this...

var m = [];
$(this).parents("tr:first").children("td").children("span").each(function(index, element)  {m.push(element.text());});  
return m.join(" - ");
like image 43
Cray Avatar answered Nov 21 '22 00:11

Cray


you could try this may feel a little heavy just not as complex.

$(this).parents("tr:first td span:eq(0)").text() + " - " + $(this).parents("tr:first td span:eq(1)").text()
like image 26
Richard Andrew Lee Avatar answered Nov 21 '22 00:11

Richard Andrew Lee