簡體   English   中英

javascript替換第一個/最后一個字母並將中間文本括入標簽

[英]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>*';
});

演示: http//jsfiddle.net/65h5cf95/3/

您將需要捕獲兩個結束字符之間的字符。 這樣的替換正則表達式會將這些字符捕獲到$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);
 }

Fiddle

replaceAt函數取自: 如何在JavaScript中的特定索引處替換字符? ,但是經過修改,使您的示例可以與<b>*</b>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM