![](/img/trans.png)
[英]javascript - replace all white spaces with html tags to enclose remaining words
[英]javascript replace first/last letter and enclose middle text into tags
我有這些股利:
<div>lorem</div>
<div>ipsum</div>
<div>dolor</div>
我想用另一個字符“ *”替換所有開頭和結尾的字母
並將其余文本(在中間)括入一個粗體標簽,如下所示:
<div>*<b>ore</b>*</div>
<div>*<b>psu</b>*</div>
<div>*<b>olo</b>*</div>
對於第一個和最后一個字母,我使用的是:
$('div').each(function(){
var thisTeXt = $(this).html();
thisTeXt = thisTeXt.replace(/(^.)|(.)$/gm,'<b>*</b>');
$(this).html(thisTeXt);
});
但是我不知道如何將中間文本包含在粗體標簽中。
使用捕獲組將中間副本復制到替換副本中:
thisText = thisText.replace(/^.(.*).$/, '*<b>$1</b>*');
您可以使用html
方法更改內容,這比使用each
方法更容易。
無需使用正則表達式即可進行簡單的字符串操作,您可以使用substr
方法獲取除第一個和最后一個字母之外的內容,然后在其前添加*<b>
在其后添加</b>*
:
$('div').html(function(i, html){
return '*<b>' + html.substr(1, html.length - 2) + '</b>*';
});
您將需要捕獲兩個結束字符之間的字符。 這樣的替換正則表達式會將這些字符捕獲到$1
變量中。
replace(/^.(.*).$/m, '*<b>$1</b>*')
工作示例:
$('div').each(function(){ var thisTeXt = $(this).html(); thisTeXt = thisTeXt.replace(/^.(.*).$/m, '*<b>$1</b>*'); $(this).html(thisTeXt); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div>lorem</div> <div>ipsum</div> <div>dolor</div>
嘗試這個,
$('div').each(function(){
var thisTeXt = $(this).html();
thisTeXt = thisTeXt
.replace(/(^.)/gm,'*<b>')
.replace(/(.)$/gm, '</b>*');
$(this).html(thisTeXt);
});
嘗試(不使用正則表達式)
$(document).ready(function(){
$('div').each(function(){
var thisTeXt = $(this).html();
thisTeXt =thisTeXt.replaceAt(0,'*');
thisTeXt =thisTeXt.replaceAt(thisTeXt.length-1,'*');
$(this).html(thisTeXt);
});
});
String.prototype.replaceAt=function(index, character) {
character="<b>"+character+"</b>";
return this.substr(0, index) + character + this.substr(index+1);
}
replaceAt
函數取自: 如何在JavaScript中的特定索引處替換字符? ,但是經過修改,使您的示例可以與<b>*</b>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.