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

时间:2014-12-27 18:37:53

标签: javascript jquery replace

我有这些div:

<div>lorem</div>
<div>ipsum</div>
<div>dolor</div>

我想用另一个字符替换所有的第一个和最后一个字母&#34; *&#34;
并将剩余的文本(中间)括在一个粗体标记中,如下所示:

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

但我不知道如何将中间文字括在粗体标签中。

DEMO HERE

5 个答案:

答案 0 :(得分:1)

使用捕获组将中间复制到替换中:

thisText = thisText.replace(/^.(.*).$/, '*<b>$1</b>*');

答案 1 :(得分:1)

您可以使用html方法更改内容,这比使用each方法更容易。

不需要正则表达式来进行简单的字符串操作,您可以使用substr方法获取除第一个和最后一个字母之外的内容,然后只需在它之前添加*<b>并{{1} 1}}之后:

</b>*

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

答案 2 :(得分:0)

您需要捕获两个结束字符之间的字符。像这样的替换正则表达式会将这些字符捕获到$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>

答案 3 :(得分:0)

试试这个,

$('div').each(function(){
    var thisTeXt = $(this).html();
    thisTeXt = thisTeXt
                       .replace(/(^.)/gm,'*<b>')
                       .replace(/(.)$/gm, '</b>*');
    $(this).html(thisTeXt);
});

答案 4 :(得分:0)

尝试(没有正则表达式)

$(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功能来自:How do I replace a character at a particular index in JavaScript?,但经过修改后,您的示例可以使用<b>*</b>