是否有一个javascript函数将字符转换为&代码; 当量?

Nul*_*uli 5 javascript jquery ckeditor

有用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)
Run Code Online (Sandbox Code Playgroud)

但这是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)
Run Code Online (Sandbox Code Playgroud)

请注意,我使用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.
Run Code Online (Sandbox Code Playgroud)

我正在使用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.
Run Code Online (Sandbox Code Playgroud)

有没有人对此有任何想法?

Ben*_*Lee 1

对 html 实体进行编码str(如果我理解正确的话,你的问题标题要求这样做):

$('<div/>').text(str).html();
Run Code Online (Sandbox Code Playgroud)

解码 html 实体str

$('<div/>').html(str).text();
Run Code Online (Sandbox Code Playgroud)

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

对 html 实体进行编码str

var el = document.createElement('div');
el.innerText = str;
el.innerHTML;
Run Code Online (Sandbox Code Playgroud)

解码 html 实体str

var el = document.createElement('div');
el.innerHTML = str;
el.innerText;
Run Code Online (Sandbox Code Playgroud)

  • 我在这里*完全*使用 dom 的唯一原因是因为浏览器已经内置了强大的、经过充分测试的实体转换方法;这只是使用 dom 来利用这种力量。 (2认同)