简体   繁体   中英

Wrap span around only numbers with jQuery

How can I wrap a span around the numbers (and only the numbers) in the table cells with class "data" and not the $ character?

Here's the HTML markup:

<table>
    <tr>
        <th>Description</th>
        <th>Weight</th>
        <th>Views</th>
        <th>Cost</th>
    </tr>

    <tr>
        <td>Item description here</td>
        <td class="data">37 pounds</td>
        <td class="data">132 views</td>
        <td class="data">$99.59</td>
    </tr>
</table>

You need to use a Regular Expression to match the numbers and wrap them with a span .

var rxp = new RegExp("([0-9]+\.?[0-9]+)", "gm");
$("td.data").each(function(){
    var $this = $(this);
    var content = $this.html();
    $this.html(content.replace(rxp, "<span>$1</span>"));
});

See test case on jsFiddle

You can use regex:

var searchPattern = new RegExp(/^\d+$/, 'g');
$elem = $('td.data');
$elem.html($elem.html().replace(searchPattern , "<span>" + searchPattern  + "</span>"));

Where, $elem is the jQuery object for the HTML element you are searching in, ie all TD with class 'data'.

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