我具有以下跨度,这些跨度在标签内包含白色间距和文本-在这种情况下为sup标签和p标签:
<span class="teamName">
Dr.<sup>J</sup>
W
Smith
<br>
<p class="department">Throat specialist</p>
</span>
我正在尝试提取'Dr. J W Smith”,但无法弄清楚该如何做。到目前为止,我有这个:
jQuery('span[class="teamName"]').text()
,它为我提供以下输出:
"
Dr.J
W
Smith
Throat specialist
"
据我所知,我正在考虑剥离白色间距并将每个单词放入数组中,然后删除最后一个条目,有人对如何进行此操作有任何想法吗?
答案 0 :(得分:0)
最简单的方法可能是克隆元素,从元素中删除br
和p
,然后获取其文本,用单个空格替换所有空白,然后修剪它:
// Here I'm assuming you have more than one
// of these, so this produces an array
var names = jQuery("span.teamName")
.clone()
.find("br, p").remove().end()
.map(function() {
return $(this).text().replace(/\s+/g, " ").trim();
}).get();
console.log(names);
<span class="teamName">
Dr.<sup>J</sup>
W
Smith
<br>
<p class="department">Throat specialist</p>
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
如果只有一个,我们可以避免使用map
:
// Here I'm assuming you have more than one
// of these, so this produces an array
var name = jQuery("span.teamName")
.clone()
.find("br, p").remove().end()
.text()
.replace(/\s+/g, " ")
.trim();
console.log(name);
<span class="teamName">
Dr.<sup>J</sup>
W
Smith
<br>
<p class="department">Throat specialist</p>
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 1 :(得分:0)
您可以使用clone()
功能
var cloned = $('.teamName').clone();
cloned.find('p').remove();
console.log(cloned.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="teamName">
Dr.<sup>J</sup>
W
Smith
<br>
<p class="department">Throat specialist</p>
</span>
答案 2 :(得分:0)
这可能对您有用。
var $span = $('.teamName').clone();
$span.find('p').remove();
alert($span.text().replace(/[ \n]+/g, ' '));