简体   繁体   English

用HTML替换字符串文本

[英]Replace String Text with HTML

I'm trying to implement emoticons so for example :happy: should display an emoticon. 我正在尝试实现表情,所以例如:happy:应该显示一个表情。 However, the text is sanitized and does not generate the actual html. 但是,该文本已被清理,不会生成实际的html。

How can I replace certain strings such as :happy: with html image? 如何用html图像替换某些字符串,例如:happy:

Current attempt (replace :happy: with html): 当前尝试(用HTML替换:happy: :):

  var data = snapshot.val();
  var username = data.name || "anonymous";
  var message = data.text;

  // REPLACE STRING WITH IMAGE
  message = message.replace(":happy:", "<img src='https://s3-us-west-1.amazonaws.com/static/emoticons/1.0.jpg'>");

  //CREATE ELEMENTS MESSAGE & SANITIZE TEXT
  var messageElement = $("<li>");
  nameElement.text(username);
  messageElement.text(": "+message).prepend(nameElement);

  //DISPLAY MESSAGE
  messageList.append(messageElement)

Update: 更新:

I think something like text.splitText() should be used here. 我认为应该在这里使用诸如text.splitText()类的东西。 But I'm trying to find the best way to find the text, then split it. 但是我正在尝试找到find文本然后split文本的最佳方法。

Use .html() to have an element effect. 使用.html()具有元素效果。 .text() will just put the content without having any HTML effect .text()只会放置内容而没有任何HTML效果

messageElement.html(": "+message).prepend(nameElement);

You can use a single detached DOM element to sanitize the inputs, then convert strings to images. 您可以使用单个分离的DOM元素清理输入,然后将字符串转换为图像。

Done by setting Node.textContent [ mdn ] and getting Element.innerHTML [ mdn ] on the detached node. 通过设置Node.textContent [ mdn ]并在分离的节点上获取Element.innerHTML [ mdn ]来完成。
Then using String.prototype.replace() [ mdn ] method on the resulting string. 然后对结果字符串使用String.prototype.replace() [ mdn ]方法。

This is library free . 这是免费的图书馆

 var username = "anonymous", message = "Some text with an happy <b>emoticon</b> :happy: and a sad <i>emoticon</i> :sad:.", messageList = document.getElementById("messageList"), sanitizer = document.createElement("p"); //CREATE ELEMENTS MESSAGE var messageElement = document.createElement("li"); //SANITIZE TEXT sanitizer.textContent = message; message = sanitizer.innerHTML; //REPLACE STRING WITH IMAGE message = message.replace(":happy:", "<img src='https://s3-us-west-1.amazonaws.com/horde.tv/static/emoticons/1.0.jpg'>"); message = message.replace(":sad:", "<img src='https://static-cdn.jtvnw.net/emoticons/v1/86/1.0'>"); messageElement.innerHTML = username + ": " + message; //DISPLAY MESSAGE messageList.appendChild(messageElement); 
 <ul id="messageList"></ul> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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