[英]With jquery, match single character followed by colon and wrap in span tag
如果我有以下html:
<p>e: 1-800-hello-49</p>
<p>another line</p>
<p>
f: 1-800-hello-49
g: 1-800-hello-49
</p>
我希望能夠在行首檢測到一個字符,然后檢測到一個冒號,以便獲得以下輸出:
<p><span>e:</span> 1-800-hello-49</p>
<p>another line</p>
<p>
<span>f:</span> 1-800-hello-49
<span>g:</span> 1-800-hello-49
</p>
我曾嘗試過使用正則表達式,但是在這種情況下我很難掌握正則表達式。
嘗試
$('p').html(function(idx, html){
return html.replace(/\b([a-z]:)/ig, '<span>$1</span>')
})
演示: 小提琴
var pattern = /^\s*(.:)/gm;
$('p').html(function(i, $html) {
return $html.replace(pattern, '<span>$1</span>');
});
您可以嘗試以下方法:
$('p').each(function() {
var html = $(this).html();
if(html.charAt(1) == ':')
{
$(this).html( '<span>' + html.charAt(0) + '</span>' + html.substr(2) );
}
});
當然,這僅適用於jQuery。 如果您使用香草javascript,請告訴我,以便我更新代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.