简体   繁体   English

如何使用JavaScript从id属性中去除非数字字符

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

I am reading the id from a list tag an add it to a pre tag like this: 我正在从列表标签中读取ID,然后将其添加到pre标签中,如下所示:

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

for example, the list tag has this id: 例如,列表标记具有以下ID:

<li id="Comment_123">

For the pre tag, I want to remove the first 8 characters from the id; 对于pre标签,我想从ID中删除前8个字符; so the pre tag should become this id: 所以pre标签应该变成这个id:

<pre id="123">  

How can I achieve this with the code I already have? 如何用已有的代码实现这一目标?

如果您知道所有ID具有相同的结构,则可以删除_(含)之前的内容。

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

If it's set at the first 8 chars, then use substring 如果设置为前8个字符,则使用substring

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

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

If you want to strip everything except digits, you could use .replace(/\\D/g, '') : 如果要.replace(/\\D/g, '')数字以外的所有内容,可以使用.replace(/\\D/g, '')

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

In other words, all occurrences of any non-digit character(s) are replaced with an empty string, '' . 换句话说,所有出现的任何非数字字符都将替换为空字符串''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM