I am reading the id from a list tag an add it to a pre
tag like this:
$('pre').each(function() {
$(this).attr('id', $(this).closest('li').attr('id'));
});
for example, the list tag has this id:
<li id="Comment_123">
For the pre tag, I want to remove the first 8 characters from the id; so the pre tag should become this 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
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, '')
:
$('pre').each(function () {
this.id = $(this).closest('li').attr('id').replace(/\D/g, '');
});
\\D
- Matches any non-digit character . g
is a global flag to match all occurrences. In other words, all occurrences of any non-digit character(s) are replaced with an empty string, ''
.
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.