是否可以在 div
中找到某些特定文本,然后按字母顺序对其进行排序?
例如,在 div
中的此文本 block 中:
<div class="text-block">
Jim, Mike, Ali, and Marsha went to the store.
</div>
我想让Jim、Mike、Ali 和 Marsha
按字母顺序排序,这样输出就会是这样的:
<div class="text-block">
Ali, Jim, Marsha, and Mike went to the store.
</div>
我觉得这几乎是不可能的,但也许只是查找并替换?不太确定最好的方法是什么。
最佳答案
您可以使用正则表达式来完成此操作。这样您就可以支持更通用的输入。
$(".text-block").html(function(idx, oldhtml) {
return oldhtml.replace(/[, a-z]+and [a-z]+/gi,function(a) {
tmp = a.replace(" and "," ").split(/[^\w]+/).sort();
return tmp.slice(0,-1).join(", ") + ", and " + tmp.pop();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-block">
Jim, Mike, Ali, and Marsha went to the store.
</div>
关于javascript - 使用 jQuery 按字母顺序对 div 中的文本进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44316536/