我正在使用test和replace方法来检测和替换文本中的标签 但是replace方法返回与tag相关联的文本,而应该只返回没有tag的文本! 为什么呢?
我的jquery插件:
jQuery.fn.extend({
insertTag: function(Tag){
var pattern = new RegExp("\[("+Tag+")\](.*?)\[\/("+Tag+")\]","gi");
return this.each(function (i) {
var sel,ptrn;
if (document.selection) {
this.focus();
sel = document.selection.createRange();
sel.text = '['+Tag+']' + sel.text + '[/'+Tag+']';
}
else if (this.selectionStart || this.selectionStart == '0') {
this.focus();
var startPos = this.selectionStart, endPos = this.selectionEnd;
sel = this.value.substring(startPos, endPos);
alert(sel); // show seleced text for debug ing!
if(pattern.test(sel)){
txt = sel.replace(pattern,"$1");
alert(txt); // show replaced text for debug ing!
this.value = this.value.substring(0, startPos) + (txt) + this.value.substring(endPos, this.value.length);
}else{
this.value = this.value.substring(0, startPos) + ('['+Tag+']' + sel + '[/'+Tag+']') + this.value.substring(endPos, this.value.length);
}
}
})
}
});
此部分用于删除所选文本中的标记(如果存在):
if(pattern.test(sel)){
txt = sel.replace(pattern,"$1");
alert(txt); // show replaced text for debug ing!
this.value = this.value.substring(0, startPos) + (txt) + this.value.substring(endPos, this.value.length);
}
但它无法正常工作......
例如:
txt = $("#txt");
txt.insertTag(b):
[b]some text[/b]
txt.insertTag(b):
[]some text[/b]
虽然返回“某些文字”
感谢您的帮助:)