我需要一些 Regexp Javascript/JQuery 方面的帮助。我成功了,但我认为还有更好、更简单的解决方案。
想法是:
如果在 button
点击,target
内部 html 有标签 <b></b>
任何地方 - 删除它们,否则添加标签 <b>
在开始和</b>
最后。
这是代码:jsFiddle example
<input id="button" type="button" value="Bold it"/>
<div id="target">This is <b>sample</b> text</div>
$(function(){
$('#button').click(function(){
var t = $('#target');
//: search for '</b>' too ???
var isFound = t.html().search(new RegExp(/<b>/i));
if(isFound >= 0) //: make 2 replaces into 1 ???
t.html(t.html().replace(/<b>/,'').replace(/<\/b>/,''))
else
t.html('<b>'+t.html()+'</b>')
})
})
问题在代码中注释:
如何搜索
<b>
和</b>
制作
.replace(/<b>/,'').replace(/<\/b>/,'')
在一个.replace(/<b>...?..../,'')
最佳答案
这不是正则表达式的用武之地,因为表达式失败的方式有很多种。参见 RegEx match open tags except XHTML self-contained tags出于幽默的原因。
尝试使用 t.children("b");
找到 <b>...</b/>
的实例在你的标签中。
在这种情况下,请尝试以下操作:
t.children("b").each(function() {
var contents = $(this).contents();
$(this).replaceWith(contents);
});
或完全展开:
$(function(){
$('#button').click(function(){
var t = $('#target');
t.children("b").each(function() {
var contents = $(this).contents();
$(this).replaceWith(contents);
});
});
});
关于JavaScript 正则表达式 : search and replace tags in string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8096639/