简体   繁体   English

从textarea中的选择中删除封闭的html标签

[英]Remove enclosing html tags from selection in textarea

I am working on a custom CMS and want to be able to select a section of HTML displayed for editing in a textarea and replace any enclosing tags with another tag. 我正在使用自定义CMS,并且希望能够选择显示的HTML部分以在文本区域中进行编辑,并将任何封闭的标签替换为另一个标签。 For instance, I may want to select a paragraph element and turn it into an h3 with one click, leaving any other tags untouched. 例如,我可能想选择一个段落元素,然后一键将其变成h3,而其他所有标签都保持不变。

I have implemented rangyinputs to allow getSelection/replaceSelectedText operations on textareas, and so far I have this: 我已经实现rangyinputs,以允许对textareas进行getSelection / replaceSelectedText操作,到目前为止,我已经做到了:

function add_html_tag(target_ID, replace_tag) {
  $(target_ID).focus();
  $(target_ID).replaceSelectedText('<' + replace_tag + '>' + $(target_ID).getSelection().text.replace(/(<([^>]+)>)/ig,"") + '</' + replace_tag + '>');
}

This works OK but it removes ALL tags from the target text, not just the enclosing ones so any other tags within the selected text would also be removed. 可以,但是可以从目标文本中删除所有标签,而不仅仅是封闭的标签,因此所选文本中的所有其他标签也将被删除。

Any ideas, I think it will just involve changing the regex in the replace statement. 任何想法,我认为这仅涉及在replace语句中更改正则表达式。 Since the textarea contains just plain text I can't use jQuery methods such as unwrap. 由于textarea仅包含纯文本,因此我无法使用jQuery方法,例如unwrap。 Obviously doing regex operations like this on HTML is error prone, but for now I will presume users select the text correctly! 显然,在HTML上执行这样的正则表达式操作很容易出错,但是现在我将假定用户正确选择文本!

this demo turns "A" tags into "LINK" tags; 该演示将“ A”标签转换为“ LINK”标签; invalid, but shows the functionality you describe: 无效,但显示您描述的功能:

function add_html_tag(target_ID, replace_tag, new_tag_name) {
  var elm=$("#"+target_ID).focus()[0];
  elm.value=elm.value.replace(  new RegExp("<(\\\/?)"+replace_tag+"\\b", "gi"), "<$1"+new_tag_name);
}

add_html_tag(textAreaID, "a", "link");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM