JavaScript 替换第一个/最后一个字母并将中间文本括在标签中

javascript replace first/last letter and enclose middle text into tags

本文关键字:文本 中间 标签 第一个 替换 最后一个 JavaScript      更新时间:2023-09-26

我有这些div:

<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);
});

TRY (不带正则表达式)

$(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>