Hazard Hazard - 4 months ago 10
jQuery Question

How to trim last two characters of each element in an array?

Here I am getting an array of width values. As it contains

px
in the end of each element. I need to trim
px
and store it in the array.

HTML

<table id="mytable">
<thead>
<tr>
<th style="width:40px;display:none;">Head1</th>
<th style="width:50px">Head2</th>
<th style="width:60px">Head3</th>
<th style="width:70px">Head4</th>
<th style="width:80px">Head5</th>
</tr>
</thead>
<tbody>
<tr>
<td style="width:40px;display:none;">1</td>
<td style="width:50px">2</td>
<td style="width:60px">3</td>
<td style="width:70px">4</td>
<td style="width:80px">5</td>
</tr>
</tbody>
</table>


Jquery

var listWidth = $("#mytable tr th").map(function() {
if($(this).is(":visible")){
return this.style.width;
}
}).get();
for (var i = 0; i < listWidth.length; i++) {
listWidth[i].slice(0, -1);
}
console.log(listWidth);


I've tried using
slice
but, no result.

Demo fiddle

Answer

Use width(). widht() will give you the numeric width without px.

return $(this).width();

:visible can be combined with the selector.

Code:

var listWidth = $("#mytable tr th:visible").map(function () {
    return $(this).width();
}).get();

Updated Fiddle


Update

I want the inline styled css width

var listWidth = $("#mytable tr th:visible").map(function () {
    return parseInt(this.style.width, 10) || $(this).width();
    // return +($(this).attr('style').match(/width:\s*(\d+)/i) || [])[1] || $(this).width();
}).get();

Fiddle Demo

Updated Fiddle

Explanation of +($(this).attr('style').match(/width:\s*(\d+)/i) || [])[1] || $(this).width();

  1. $(this).attr('style'): Get the style attribute value
  2. .match(/width:\s*(\d+)/i): Match the string width: followed by any number of spaces, followed by one or more digits. i is case-insensitive flag.
  3. (foo || []): If foo is falsey, use empty array. match will return null if no match is found.
  4. [1]: Get the string in the first captured group.
  5. +something: Convert to Number
  6. || $(this).width(): Get computed width if inline width is not available.