我有一个文本字符串,例如:
<div id="ideal">The quick brown fox jumps over the lazy Stack Overflow user</div>
我想用 HTML 包装最后一个词('user')以生成:
<div id="ideal">
The quick brown fox jumps over the lazy
Stack Overflow <span class="foo">user</span>
</div>
到目前为止,我已经使用空格拆分字符串并考虑替换匹配项,但大多数解决方案都使用正则表达式,但正则表达式可能是字符串中其他地方重复的单词。
我目前使用子字符串进行以下工作:
var original = document.getElementById("ideal").textContent;
var para = original.split(" ");
var paracount = para.length;
var wordtoreplace = para[paracount-1];
var idx = original.lastIndexOf(wordtoreplace);
var newStr = original.substring(0, idx) + '<span class="foo">' + wordtoreplace + '</span>';
但这只适用于纯 javascript,而不是作为跨越 <div class="ideal">
的许多实例的可重复函数。
是否有一种可重复的方式使用 javascript 或 jQuery 对 <div class="ideal">
的一个或多个实例执行此操作(通过类而不是 id) ?
最佳答案
你可以这样做:
$('.ideal').each(function() {
var $this = $(this);
$this.html($this.html().replace(/(\S+)\s*$/, '<span class="foo">$1</span>'));
});
关于javascript - 查找文本字符串中的最后一个单词并用 HTML 换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16259108/