有没有一种JavaScript函数可以将字符转换为&code;等效形式?

5
我有一些使用CKeditor创建的文本,它似乎会在应该有空格的地方插入&nbsp;。它还会对>、<、&等进行类似的转换,这很好,但是当我创建DOMSelection时,这些代码会被移除。
因此,这就是所选择的内容:
before<a href=\"http://wiki.teamliquid.net/starcraft2/Hatchery\" style=\"text-decoration: none; color: rgb(0, 43, 184); background-image: none; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: initial; background-position: initial initial; background-repeat: initial initial; \" title=\"Hatchery\">Hatchery</a> (2)

但实际上这才是DOM中的内容:

before<a href=\"http://wiki.teamliquid.net/starcraft2/Hatchery\" style=\"text-decoration: none; color: rgb(0, 43, 184); background-image: none; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: initial; background-position: initial initial; background-repeat: initial initial; \" title=\"Hatchery\">Hatchery</a>&nbsp;(2)

请注意,我使用variable.inspect输出了存储在数据库中的选择和原始文本,因此所有引号都被转义了(发送到浏览器时不会这样)。
为了让大家省去寻找差异的痛苦:
从第一个: Hatchery</a> (2)(选择)
从第二个: Hatchery</a>&nbsp;(2)(原始文本)
这些差异位于选择的末尾。
那么......我能看到三种方法来处理这个问题。
1) - Replace all characters commonly replaced with codes with their codes, 
     and hope for the best.
2) - Javascript may have some uncommon function / a library may exist that 
     replaces these characters for me (I think this might be the way CKeditor 
     does its character conversion).
3) - Figure out the way CKeditor converts and do the conversion exactly that way.

我是Ruby on Rails的用户,但这对于这个问题并不重要。
我发现它还转换了一些其他的东西:
1: It seems to only convert spaces to &nbsp; if the space(s) is before or after a tag:
   e.g.: "With quick&nbsp;<a href..."
2: It changes apostrophes to the hex value
   e.g.: "opponent&#39;s"
3: It changes "&" to "&amp;"
4: It changes angle brackets to "&gt;" and "&lt;" appropriately.

有人对此有什么想法吗?


1
我的想法是使用一个文本编辑器,它不会在未经允许的情况下转换任何内容。 - kennebec
我希望能使用Aloha Editor,但不幸的是这不是我的决定。=( - NullVoxPopuli
2个回答

1

1

如果我理解正确,要在str中编码HTML实体:

$('<div/>').text(str).html();

要解码 str 中的 HTML 实体:

$('<div/>').html(str).text();

这些依赖于jQuery,但是基于vanilla的替代方案基本相同,只是更冗长。

要在str中编码HTML实体:

var el = document.createElement('div');
el.innerText = str;
el.innerHTML;

要解码 str 中的 HTML 实体:

var el = document.createElement('div');
el.innerHTML = str;
el.innerText;

当您使用.text()时,会丢失DOM结构。由于原始文本包含所有的DOM标记,因此我需要确保保留它们。 - NullVoxPopuli
@TheLindyHop,我不明白你的意思。我可能误解了你的问题,但是听起来这与dom结构无关。你有一个字符串,想要编码实体(也就是将像“ ”=>&nbsp;这样的东西转换)或者解码实体(将像&nbsp;=>“ ”这样的东西转换)。 - Ben Lee
哦,等等!我可以使用.outerHTML来获取我的str变量。 - NullVoxPopuli
2
我在这里使用DOM的唯一原因是因为浏览器已经内置了强大且经过充分测试的实体转换方法;这只是利用DOM来发挥其威力。 - Ben Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接