有几种方法可以做到这一点,基本是找到最后一部分,然后使用最后一部分:
// 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>
参考资料: