簡體   English   中英

如何使用JavaScript從id屬性中去除非數字字符

[英]How to strip non-digit characters from an id attribute with JavaScript

我正在從列表標簽中讀取ID,然后將其添加到pre標簽中,如下所示:

$('pre').each(function() {
  $(this).attr('id', $(this).closest('li').attr('id'));
});

例如,列表標記具有以下ID:

<li id="Comment_123">

對於pre標簽,我想從ID中刪除前8個字符; 所以pre標簽應該變成這個id:

<pre id="123">  

如何用已有的代碼實現這一目標?

如果您知道所有ID具有相同的結構,則可以刪除_(含)之前的內容。

var id = $(this).closest('li').attr('id').split('_').pop();

如果設置為前8個字符,則使用substring

var id = $(this).closest('li').attr('id');
var shortened = id.substring(8, id.length);

$(this).attr('id', shortened);

如果要.replace(/\\D/g, '')數字以外的所有內容,可以使用.replace(/\\D/g, '')

$('pre').each(function () {
  this.id = $(this).closest('li').attr('id').replace(/\D/g, '');
});

換句話說,所有出現的任何非數字字符都將替換為空字符串''

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM