简体   繁体   English

Javascript-将HTML标记从textarea替换为div

[英]Javascript - Replace HTML tag from textarea to div

For personnal purpose I am trying to create a code editor using a div (z-index 1) and a textarea (z-index 2, opacity 0.2). 出于个人目的,我试图使用div(z索引1)和textarea(z索引2,不透明度0.2)创建代码编辑器。

Using JQuery and a keyUp event, I am replacing the text of the textarea using .html() on the div, after replacing all tags in colored tags. 使用JQuery和keyUp事件,在替换彩色标签中的所有标签之后,我将在div上使用.html()替换textarea的文本。

But I got a strange but that I cannot explain. 但是我很奇怪,但是我无法解释。 I am using the following code : 我正在使用以下代码:

str.replace('/</g', "&lt;");

This does not seems to work. 这似乎不起作用。 Writing "test <" will show "test <", but writing any more letter will cut off the text. 写“ test <”将显示“ test <”,但是再写字母将切断文本。

For example : 
- Example : "test <i" will show "test ".
- Example 2 : "test < a <i" will show "test < a ".
- Keep in mind : Actually, "test <" show "test <", not "test &lt;".

(Example seems to be broken on stackoverflow, so I used to indent the examples) (示例似乎在stackoverflow上被破坏了,因此我习惯于缩进示例)

Any Idea ? 任何想法 ?

The javascript engine sees your regex as a string, and searches for the string instead, you need to remove the quotes JavaScript引擎将您的正则表达式视为字符串,然后搜索该字符串,则需要删除引号

"test < a <i".replace(/</g, "&lt;");

An unclosed tag will be closed by the browser, that is why you won't see <i as text 未关闭的标签将被浏览器关闭,这就是为什么您不会看到<i作为文本的原因

Got this working with this code, for example : 使用此代码进行此操作,例如:

str = str.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/&lt;title&gt;/, "<span style='color:blue;'>&lt;title&gt;</span>");

Thanx ! 谢谢!

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

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