Hazard Hazard - 1 year ago 93
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

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


<table id="mytable">
<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>
<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>


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

I've tried using
but, no result.

Demo fiddle

Answer Source

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

return $(this).width();

:visible can be combined with the selector.


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

Updated Fiddle


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();

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download