Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

javascript - convert string that contains <,> (Special chars) to html

I have a string that is, <some text>
I'm trying to highlight the "te" in it, using replace function

 InnerHTML = innerHTML.replace(some_Regex_Pattern['te'], '<span style='background-color:#FFFB00'>$&</span>');

The string I obtain is,

<some <span class='highlight' style='background-color:#FFFB00'>te</span>xt>

Now setting this to element.innerHTML, is considered as an HTML tag, causing problem.
In DOM I get the element as

<some <span class='highlight' style='background-color:#FFFB00'>te</span>xt></some>

I get the string in malformed form, how can I convert it to correct format, without making changes to the correct html tag i.e here?

How can I solve this issue,.. If it is not understandable, please comment,..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to replace < by &lt; and > by &gt; before replacing the te.

innerHTML.replace('<', '&lt;').replace('>', '&gt;')...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...