JavaScript 替换第一个/最后一个字母并将中间文本括在标签中
javascript replace first/last letter and enclose middle text into tags
我有这些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>
相关文章:
- 如何使用JS在中间输入文本中动态插入字符
- 在每个条形图的中间添加文本标签&鼠标悬停事件
- 在输入文本框的文本中间插入键盘字符值
- Beautifulsoup抓取数据,其中有js文本在中间
- 时刻.js以日期中间格式包含文本
- createElement-选择穿插在文本中间的框
- 如何使用 Javascript 从字符串中间提取然后重新格式化文本
- JavaScript 替换第一个/最后一个字母并将中间文本括在标签中
- 在按键事件上对齐页面中间的文本框
- 如何在焦点上垂直设置文本区域/输入中间的默认光标插入符号
- 计算圆心以在中间对齐文本
- 拆分文本节点在中间
- 始终将插入符号保持在文本区域的垂直中间
- 如何在两个不断变化的字符串之间选择中间文本
- CSS / Javascript微调器对齐文本中间
- 如何查找html元素是否应用了换行,并且该单词在文本中间断开
- asp.net使用jquery和javascript来确定与按钮匹配的文本框ID的中间部分
- jQuery Mobile:尝试在某些文本中间显示一个图标
- 如何在文本中间显示文本溢出省略号
- 如何在文本中间显示额外的跨度