在#个内容文本之前插入span标签 [英] Insert span tag before # content text
本文介绍了在#个内容文本之前插入span标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何使用jquery在#号内容之前插入span标签.对不起,这个问题.我还是jquery新手.
i want to know how to insert span tag before the # sign content using jquery. Sorry for this question. I'm still new to jquery.
<script>
$(document).ready(function() {
var text = $(".name a").text();
//alert(text);
if (text.contains("#")) {
alert("yes");
}
else {
alert("no");
}
});
</script>
<div class="name">
<a href="">This is a link contens #104004</a>
</div>
输出应该像这样
<div class="name">
<a href="">This is a link contens <span>#104004</span></a>
</div>
推荐答案
尝试以下示例:
$(document).ready(function() {
var
textElement = $(".name > a"),
text = textElement.text();
textElement.html(text.replace(/#[0-9]+/g, '<span>$&</span>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="name">
<a href="">This is a link contens #104004</a>
</div>
结果:
更新:
面向对象的JavaScript-第二版 :
replace()
允许您将匹配的文本替换为其他字符串.当一个 如果您想将匹配的文本包括在匹配项中,则找到匹配项 替换字符串,您可以使用$&.
Object-Oriented JavaScript - Second Edition:
replace()
allows you to replace the matched text with some other string. When a match is found, if you want to include the matched text in the replacement string, you can access it using $&.
示例:
var s = 'HelloJavaScriptWorld';
s.replace(/[A-Z]/g, "_$&"); // "_Hello_Java_Script_World"
这篇关于在#个内容文本之前插入span标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文