gpt4 book ai didi

jQuery - 按符号分割字符串并获取最后一部分

转载 作者:行者123 更新时间:2023-12-01 03:09:04 25 4
gpt4 key购买 nike

如果我有如下银行帐号列表:

<span>6456465465/0471</span>
<span>4547/6456465465/0471</span>
<span>4547/6465465/0471</span>

如何获取每个数字的最后四位数字?有些银行账户有前缀,有些则没有。

我的代码仅适用于第一个跨度,因为帐户的其余部分都有前缀。

$("span").each(function(){
var kodBanky = $(this).text().split("/")[1];
$('body').append("<p>" + kodBanky + "</p>");
});

Codepen

最佳答案

有几种方法可以做到这一点,基本方法是找到最后一部分,然后使用最后一部分:

// iterate over each <span>:
$("span").each(function() {
// find the text of the current <span>, split
// on the '/' characters, and retrieve that last
// part:
var kodBanky = $(this).text().split("/").pop();

// append a newly created <p> element to the
// <body> element:
$('<p/>', {
'text' : kodBanky
}.appendTo('body');
});

$("span").each(function() {
var kodBanky = $(this).text().split("/").pop();
$('body').append("<p>" + kodBanky + "</p>");
});
span {
display: block;
margin: 0 0 0.5em 0;
border-bottom: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>6456465465/0471</span>
<span>4547/6456465465/0471</span>
<span>4547/6465465/0471</span>

值得注意的是,像这样简单的事情几乎肯定不需要 jQuery:

// get all the <span> elements in the document, and convert
// the returned collection, from document.querySelectorAll(),
// into an Array, using Array.from():
var spans = Array.from(document.querySelectorAll('span')),

// create a <p> element:
para = document.createElement('p'),

// two variables for later use:
clone,
code;

// iterating over the Array of <span> elements:
spans.forEach(function(span) {
// 'span' refers to the current array-element,
// a <span> element, within the array of <span>
// elements over which we're iterating.

// code is the text contained within the current
// <span> after it's trimmed of its leading, and
// trailing, white-space. We then split that text
// on the '/' characters, and retrieve the last
// Array element of the Array using
// Array.prototype.pop()
code = span.textContent.trim().split('/').pop();

// we clone the paragraph:
clone = para.cloneNode();

// updating its textContent:
clone.textContent = code;

// and append that created-<p> element to
// document.body:
document.body.appendChild(clone);
});

var spans = Array.from(document.querySelectorAll('span')),
para = document.createElement('p'),
clone,
code;

spans.forEach(function(span) {
code = span.textContent.trim().split('/').pop();
clone = para.cloneNode();

clone.textContent = code;
document.body.appendChild(clone);
});
span {
display: block;
margin: 0 0 0.5em 0;
border-bottom: 1px solid #ccc;
}
<span>6456465465/0471</span>
<span>4547/6456465465/0471</span>
<span>4547/6465465/0471</span>

引用文献:

关于jQuery - 按符号分割字符串并获取最后一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37700537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com