简体   繁体   中英

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).

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.

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.

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)

Any Idea ?

The javascript engine sees your regex as a string, and searches for the string instead, you need to remove the quotes

"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

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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