转换包含<,>的字符串(特殊字符)到html [英] convert string that contains <,> (Special chars) to html

查看:53
本文介绍了转换包含<,>的字符串(特殊字符)到html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,即<一些文本>
我正在尝试使用替换功能突出显示其中的"te"

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>');

我得到的字符串是

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

现在将其设置为element.innerHTML,被视为HTML标记,从而导致问题.
在DOM中,我将元素获取为

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>

我得到格式错误的字符串,如何在不更改正确的html标签的情况下将其转换为正确的格式?

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

推荐答案

Regular expressions and HTML don't mix very well. In your case, if you're very careful you can manually escape all the proper values and produce valid HTML. If you're even a little careless you will have problems with malformed or unsafe content. This is not to say "you absolutely must never do it that way", but you should at least be aware of the pitfalls involved in doing so.

推荐的解决方案是永远不要自己以编程方式操作HTML字符串.相反,您应该操作 HTMLElement 对象并信任您的JavaScript引擎来处理HTML.

The recommended solution is never to programmatically manipulate HTML strings yourself. Instead, you should manipulate HTMLElement objects and trust your JavaScript engine to handle the HTML.

就您而言,我想说这个问题有两个部分.

In your case, I'd say there are two components to the question.

一个:将字符串转换为表示形式,其中字符串的各个部分被标记为应突出显示"或不应突出显示".如果引入以下界面(毕竟使用了TypeScript标记):

One: convert a string into a representation where pieces of the string are marked as "should-be-highlighted" or "should-not-be-highlighted". If you introduce the following interface (you used the TypeScript tag after all):

interface HighlightableString {
    value: string;
    highlighted: boolean;
}

然后,带有突出显示部分的字符串可以表示为 Array< HighlightableString> .

Then a string with highlighted sections could be represented as Array<HighlightableString>.

因此,您需要一个函数来将< some text>" 之类的字符串和"te" 子字符串转换为

So you need a function to convert a string like "<some text>" and the substring "te" to something like

[ 
  {value: "<some ", highlighted: false}, 
  {value: "te", highlighted: true}, 
  {value: "xt>", highlighted: false}
]

这是该功能的一种可能的实现,但是您可以根据需要进行任何操作.这是使用正则表达式的一个完全有效的地方,因为这里没有办法表示不安全"或格式错误"的HTML:

Here's one possible implementation of that function, but you can do it any way you want. And this is a perfectly valid place to use regular expressions, since there is no way to represent "unsafe" or "malformed" HTML here:

function highlightSubstring(s: string, substring: string): Array<HighlightableString> {
    if (substring.length === 0) return [{ value: s, highlighted: false }]
    const ret: Array<HighlightableString> = [];
    for (
      var prevPos = 0, pos = s.indexOf(substring); 
      pos >= 0; 
      prevPos = pos + substring.length, pos = s.indexOf(substring, prevPos)
    ) {
        ret.push({ value: s.substring(prevPos, pos), highlighted: false });
        ret.push({ value: substring, highlighted: true });
    }
    ret.push({ value: s.substring(prevPos), highlighted: false });
    return ret;
}

两个:给定一个 Array< HighlightableString> ,一个父类 HTMLElement 以及某种突出显示文本的方式(例如,表示这种形式的 HTMLElement 突出显示),将正确突出显示的文本添加到该父元素.在这里,您真的根本不想使用正则表达式或HTML文本.这是一种可能的实现方式:

Two: given an Array<HighlightableString>, a parent HTMLElement, and some way of highlighting text (e.g., an HTMLElement representing such highlighting), add the properly highlighted text to that parent element. This is where you really don't want to be using regular expressions, or HTML text at all. Here is one possible implementation:

function appendHighlightedString(
  highlightableStrings: Array<HighlightableString>, 
  parentElement: HTMLElement, 
  highlightElement: HTMLElement
) {
  highlightableStrings.forEach(hs => {
    const textNode = document.createTextNode(hs.value);
      if (hs.highlighted) {
          const highlightClone = highlightElement.cloneNode(true);
          highlightClone.appendChild(textNode)
          parentElement.appendChild(highlightClone)
      } else {
          parentElement.appendChild(textNode);
      }
  })
}

请注意该功能如何使用 Text 节点以及元素的克隆和附加.它永远不会直接看HTML.

Notice how that function is using Text nodes and element cloning and appending. It never looks at HTML directly.

好的,让我们看看它是否有效.我将尝试使用内容< test content> :

Okay, let's see if it works. I will try it with the content <test content>:

// make a highlight element
const highlightElement = document.createElement("span");
highlightElement.style.backgroundColor = '#FFFB00';

const wholeString = document.createElement("div"); // or whatever the parent element is
appendHighlightedString(
  highlightSubstring("<test content>", "te"), 
  wholeString, 
  highlightElement
);

让我们看看它在Firefox中的作用:

Let's see what it did in Firefox:

console.log(wholeString.innerHTML);
// &lt;<span style="background-color: rgb(255, 251, 0);">te</span>st 
// con<span style="background-color: rgb(255, 251, 0);">te</span>nt&gt;

好吧,浏览器决定使用 rgb(255,251,0)代替#FFFB00 .但这就是浏览器的特权.我们退出了HTML游戏.关键是,如果您将该元素添加到文档中,

Well, the browser decided to use rgb(255, 251, 0) instead of #FFFB00. But that's the browser's prerogative; we are out of the HTML game. The point is if you add that element to your document,

document.body.appendChild(wholeString);

它将以您想要的方式突出显示.

it will be highlighted the way you want.

好的,希望能有所帮助.祝你好运!

Okay, hope that helps. Good luck!

这篇关于转换包含&lt;,&gt;的字符串(特殊字符)到html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆