将图像添加到字符串?将单词翻译成图像

时间:2017-11-13 11:08:36

标签: javascript html string image algorithm

我想创建一个程序,让你输入一个句子,如: 我很开心。 并且输出:我是(快乐的表情符号,在我的例子中是我自己创建的图像)。

到目前为止,我可以用另一个词替换happy,但我需要用图像替换它。 我可以将图像添加到字符串中吗? 如果是这样,怎么样?

更新:我的代码终于有效了,这是我用过的html和javascript:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Parse emotional expressions with emoticions.</title>
     <style>
      .inline-img {
          height: 40px;
        }
    </style>
     </head>
      <body>
        <font size="+3" face="Helvetica">
       <p id="output"></p>
     </font>
         <script>
         document.addEventListener('DOMContentLoaded', function() {
         function word_replace(replacements, str) {
           var result = str;
            for (var [x, url] of replacements) {
             result = result.replace(x, '<img src="' + url + '" alt="emoji" class="inline-img" />');
                    }
          return result;
          }
            var input = prompt('Input your sentence');
            var output = word_replace([

            [/(happy)/ig, 'https://c1.staticflickr.com/5/4521/38517798662_418a72e9d9_b.jpg'],
            [/(sad|depressed)/ig, 'https://c1.staticflickr.com/5/4553/38517797352_6c8fba1a3d_o.png'],
            [/(confused)/ig, "https://c1.staticflickr.com/5/4519/37833334134_109952bda2_b.jpg"],
            [/(afraid)/ig, 'https://c1.staticflickr.com/5/4516/37833334324_c43f01a30d_b.jpg'],
            [/(angry)/ig, 'https://c1.staticflickr.com/5/4532/26773555349_63894fa4be_b.jpg'],
            [/(determined)/ig, 'https://c1.staticflickr.com/5/4537/37833333874_ff92cb8647_b.jpg'],
            [/(love)/ig, 'https://c1.staticflickr.com/5/4530/37833331724_8a90312ddb_b.jpg'],
            [/(indifferent)/ig, 'https://c1.staticflickr.com/5/4543/37833333744_59da46444d_b.jpg']

          ], input);


          var outputElement = document.getElementById("output");
          outputElement.innerHTML = output;
      });

    </script>
  </body>
</html>

4 个答案:

答案 0 :(得分:1)

如果您的目的是让文本在某处显示为HTML,则对替换函数的简单修改会在文本中插入<img>标记。

这样您只需提供图片链接即可。

我将正则表达式更改为包含括号,以便将捕获组用于<img>标记的替代文字。

我还使用了一个类来用css限制图像的高度。

&#13;
&#13;
function mreplace(replacements, str) {
  let result = str;
  for (let [x, y] of replacements) {
    result = result.replace(x, '<img src="' + y + '" alt="$1" class="inline-img" />');
  }
  return result;
}

let input = prompt('Input your sentence');
let output = mreplace([
  [/(happy)/ig, 'https://icon-icons.com/icons2/860/PNG/512/happy_icon-icons.com_67810.png'],
  [/(sad)/ig, 'https://images.vexels.com/media/users/17482/106930/raw/fcba42ccb55e21d86c6cc25078f0431e-cute-and-sad-icon-vector.png'],
  [/(confused)/ig, "http://i0.kym-cdn.com/photos/images/original/001/157/196/bcf.gif"]
], input);

$("#input").html(input);
$("#output").html(output);
&#13;
.inline-img {
  height: 20px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input"></div>
<div id="output"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我认为您可以尝试创建ico字体并使用它来替换某些单词等。

答案 2 :(得分:0)

&#13;
&#13;
/*
 * jQuery CSSEmoticons plugin 0.2.9
 *
 * Copyright (c) 2010 Steve Schwartz (JangoSteve)
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Date: Sun Oct 22 1:00:00 2010 -0500
 */(function(a){a.fn.emoticonize=function(m){var c=a.extend({},a.fn.emoticonize.defaults,m);var d=[")","(","*","[","]","{","}","|","^","<",">","\\","?","+","=","."];var l=[":-)",":o)",":c)",":^)",":-D",":-(",":-9",";-)",":-P",":-p",":-Þ",":-b",":-O",":-/",":-X",":-#",":'(","B-)","8-)",";*(",":-*",":-\\","?-)",": )",": ]","= ]","= )","8 )",": }",": D","8 D","X D","x D","= D",": (",": [",": {","= (","; )","; ]","; D",": P",": p","= P","= p",": b",": Þ",": O","8 O",": /","= /",": S",": #",": X","B )",": |",": \\","= \\",": *",": &gt;",": &lt;"];var j=[":)",":]","=]","=)","8)",":}",":D",":(",":[",":{","=(",";)",";]",";D",":P",":p","=P","=p",":b",":Þ",":O",":/","=/",":S",":#",":X","B)",":|",":\\","=\\",":*",":&gt;",":&lt;"];var h={"&gt;:)":{cssClass:"red-emoticon small-emoticon spaced-emoticon"},"&gt;;)":{cssClass:"red-emoticon small-emoticon spaced-emoticon"},"&gt;:(":{cssClass:"red-emoticon small-emoticon spaced-emoticon"},"&gt;: )":{cssClass:"red-emoticon small-emoticon"},"&gt;; )":{cssClass:"red-emoticon small-emoticon"},"&gt;: (":{cssClass:"red-emoticon small-emoticon"},";(":{cssClass:"red-emoticon spaced-emoticon"},"&lt;3":{cssClass:"pink-emoticon counter-rotated"},O_O:{cssClass:"no-rotate"},o_o:{cssClass:"no-rotate"},"0_o":{cssClass:"no-rotate"},O_o:{cssClass:"no-rotate"},T_T:{cssClass:"no-rotate"},"^_^":{cssClass:"no-rotate"},"O:)":{cssClass:"small-emoticon spaced-emoticon"},"O: )":{cssClass:"small-emoticon"},"8D":{cssClass:"small-emoticon spaced-emoticon"},XD:{cssClass:"small-emoticon spaced-emoticon"},xD:{cssClass:"small-emoticon spaced-emoticon"},"=D":{cssClass:"small-emoticon spaced-emoticon"},"8O":{cssClass:"small-emoticon spaced-emoticon"},"[+=..]":{cssClass:"no-rotate nintendo-controller"}};var f=new RegExp("(\\"+d.join("|\\")+")","g");var n="(^|[\\s\\0])";for(var g=l.length-1;g>=0;--g){l[g]=l[g].replace(f,"\\$1");l[g]=new RegExp(n+"("+l[g]+")","g")}for(var g=j.length-1;g>=0;--g){j[g]=j[g].replace(f,"\\$1");j[g]=new RegExp(n+"("+j[g]+")","g")}for(var k in h){h[k].regexp=k.replace(f,"\\$1");h[k].regexp=new RegExp(n+"("+h[k].regexp+")","g")}var e="span.css-emoticon";if(c.exclude){e+=","+c.exclude}var b=e.split(",");return this.not(e).each(function(){var o=a(this);var i="css-emoticon";if(c.animate){i+=" un-transformed-emoticon animated-emoticon"}for(var p in h){specialCssClass=i+" "+h[p].cssClass;o.html(o.html().replace(h[p].regexp,"$1<span class='"+specialCssClass+"'>$2</span>"))}a(l).each(function(){o.html(o.html().replace(this,"$1<span class='"+i+"'>$2</span>"))});a(j).each(function(){o.html(o.html().replace(this,"$1<span class='"+i+" spaced-emoticon'>$2</span>"))});a.each(b,function(q,r){o.find(a.trim(r)+" span.css-emoticon").each(function(){a(this).replaceWith(a(this).text())})});if(c.animate){setTimeout(function(){a(".un-transformed-emoticon").removeClass("un-transformed-emoticon")},c.delay)}})};a.fn.unemoticonize=function(b){var c=a.extend({},a.fn.emoticonize.defaults,b);return this.each(function(){var d=a(this);d.find("span.css-emoticon").each(function(){var e=a(this);if(c.animate){e.addClass("un-transformed-emoticon");setTimeout(function(){e.replaceWith(e.text())},c.delay)}else{e.replaceWith(e.text())}})})};a.fn.emoticonize.defaults={animate:true,delay:500,exclude:"pre,code,.no-emoticons"}})(jQuery);



$('.comment').emoticonize();
&#13;
/*
 * jQuery CSSEmoticons plugin 0.2.9
 *
 * Copyright (c) 2010 Steve Schwartz (JangoSteve)
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Date: Sun Oct 22 1:00:00 2010 -0500
 */
 
 /* Basic styles for emoticons */
span.css-emoticon {
  font-family: "Trebuchet MS"; /* seems to give the best and most consistent emoticon appearance */
  font-size: 0.65em;
  font-weight: bold;
  color: #000000;
  display: inline-block;
  overflow: hidden;
  vertical-align: middle;
  transform: rotate(90deg);
  -webkit-transform: rotate(90deg);
  -moz-transform: rotate(90deg);
  -o-transform: rotate(90deg);
  width: 1.54em; /* note that this is a multiple of this span's font-size, not containing text font-size */
  height: 1.54em; /* so, relative to containing text, width and height are 0.9 x 1.6 = 1.44em */
  text-align: center;
  padding: 0;
  line-height: 1.34em;
  -moz-border-radius: 1.54em;
  -webkit-border-radius: 1.54em;
  border-radius: 1.54em;
  -moz-box-shadow: 1px -1px 2px rgba(0,0,0,0.5);
  -webkit-box-shadow: 1px -1px 2px rgba(0,0,0,0.5);
  box-shadow: 1px -1px 2px rgba(0,0,0,0.5);
  border: 1px solid rgba(0,0,0,0.25);
  background-color: #ffcc00;
  background-image: -webkit-gradient(
    linear,
    right top,
    left top,
    color-stop(0.41, rgb(255,204,0)),
    color-stop(0.56, rgb(255,221,85)),
    color-stop(1, rgb(255,238,170))
  );
  background-image: -moz-linear-gradient(
    center right,
    rgb(255,204,0) 41%,
    rgb(255,221,85) 56%,
    rgb(255,238,170) 100%
  );
  -webkit-transition-property:color, background, transform;  
  -webkit-transition-duration: 1s, 1s;  
  -webkit-transition-timing-function: linear, ease-in;
}

/* Styles for two-character emoticons that need more letter-spacing for proportionality */
span.css-emoticon.spaced-emoticon {
  padding-left: 0.2em;
  width: 1.34em;
  letter-spacing: 0.2em;
}

/* This is a dirty dirty hack, because webkit doesn't properly do the padding+width=total-width as it should
   I think the width of the border may be throwing things off, because it's more noticable for small icons */
@media screen and (-webkit-min-device-pixel-ratio:0) {
  span.css-emoticon.spaced-emoticon {
    width: 1.4em;
  }
}

/* Styles for emoticons that need to have smaller characters to fit inside the circle */
span.css-emoticon.small-emoticon {
  font-size: 0.55em;
  width: 1.82em;
  height: 1.82em;
  line-height: 1.72em;
  -moz-border-radius: 1.82em;
  -webkit-border-radius: 1.82em;
  border-radius: 1.82em;
}

span.css-emoticon.small-emoticon.spaced-emoticon {
  padding-left: 0;
  width: 1.82em;
  letter-spacing: 0.1em;
}

/* Styles for additional colors */
span.css-emoticon.red-emoticon {
  background-color: #eb0542;
  background-image: -webkit-gradient(
    linear,
    right top,
    left top,
    color-stop(0.41, rgb(235,5,66)),
    color-stop(0.56, rgb(235,38,90)),
    color-stop(1, rgb(250,55,110))
  );
  background-image: -moz-linear-gradient(
    center right,
    rgb(235,5,66) 41%,
    rgb(235,38,90) 56%,
    rgb(250,55,110) 100%
  );
}

span.css-emoticon.pink-emoticon {
  background-color: #ff8fd4;
  background-image: -webkit-gradient(
    linear,
    right top,
    left top,
    color-stop(0.41, rgb(255,143,212)),
    color-stop(0.56, rgb(255,153,216)),
    color-stop(1,    rgb(255,173,225))
  );
  background-image: -moz-linear-gradient(
    center right,
    rgb(255,143,212) 41%,
    rgb(255,153,216) 56%,
    rgb(255,173,225) 100%
  );
}

/* styles for emoticons that need no rotation, like O_o */
span.css-emoticon.no-rotate { 
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
  -moz-transform: rotate(0deg);
  -o-transform: rotate(0deg);
  -moz-box-shadow: 1px 1px 2px rgba(0,0,0,0.5);
  -webkit-box-shadow: 1px 1px 2px rgba(0,0,0,0.5);
  box-shadow: 1px 1px 2px rgba(0,0,0,0.5);
  font-size: 0.45em;
  width: 2.2em;
  height: 2.2em;
  line-height: 1.9em;
  -moz-border-radius: 2.2em;
  -webkit-border-radius: 2.2em;
  border-radius: 2.2em;
  background-image: -webkit-gradient(
    linear,
    right bottom,
    right top,
    color-stop(0.41, rgb(255,204,0)),
    color-stop(0.56, rgb(255,221,85)),
    color-stop(1, rgb(255,238,170))
  );
  background-image: -moz-linear-gradient(
    center bottom,
    rgb(255,204,0) 41%,
    rgb(255,221,85) 56%,
    rgb(255,238,170) 100%
  );
}

span.css-emoticon.no-rotate.red-emoticon {
  background-image: -webkit-gradient(
    linear,
    right bottom,
    right top,
    color-stop(0.41, rgb(235,5,66)),
    color-stop(0.56, rgb(235,38,90)),
    color-stop(1, rgb(250,55,110))
  );
  background-image: -moz-linear-gradient(
    center bottom,
    rgb(235,5,66) 41%,
    rgb(235,38,90) 56%,
    rgb(250,55,110) 100%
  );
}

span.css-emoticon.no-rotate.pink-emoticon {
  background-image: -webkit-gradient(
    linear,
    right bottom,
    right top,
    color-stop(0.41, rgb(255,143,212)),
    color-stop(0.56, rgb(255,153,216)),
    color-stop(1,    rgb(255,173,225))
  );
  background-image: -moz-linear-gradient(
    center bottom,
    rgb(255,143,212) 41%,
    rgb(255,153,216) 56%,
    rgb(255,173,225) 100%
  );
}

/* Styles for emoticons that need to be rotated counter-clockwise, like <3 */
span.css-emoticon.counter-rotated { 
  transform: rotate(-90deg);
  -webkit-transform: rotate(-90deg);
  -moz-transform: rotate(-90deg);
  -o-transform: rotate(-90deg);
  -moz-box-shadow: -1px 1px 2px rgba(0,0,0,0.5);
  -webkit-box-shadow: -1px 1px 2px rgba(0,0,0,0.5);
  box-shadow: -1px 1px 2px rgba(0,0,0,0.5);
  background-image: -webkit-gradient(
    linear,
    left top,
    right top,
    color-stop(0.41, rgb(255,204,0)),
    color-stop(0.56, rgb(255,221,85)),
    color-stop(1, rgb(255,238,170))
  );
  background-image: -moz-linear-gradient(
    center left,
    rgb(255,204,0) 41%,
    rgb(255,221,85) 56%,
    rgb(255,238,170) 100%
  );
}

span.css-emoticon.counter-rotated.red-emoticon {
  background-image: -webkit-gradient(
    linear,
    left top,
    right top,
    color-stop(0.41, rgb(235,5,66)),
    color-stop(0.56, rgb(235,38,90)),
    color-stop(1, rgb(250,55,110))
  );
  background-image: -moz-linear-gradient(
    center left,
    rgb(235,5,66) 41%,
    rgb(235,38,90) 56%,
    rgb(250,55,110) 100%
  );
}

span.css-emoticon.counter-rotated.pink-emoticon {
  background-image: -webkit-gradient(
    linear,
    left top,
    right top,
    color-stop(0.41, rgb(255,143,212)),
    color-stop(0.56, rgb(255,153,216)),
    color-stop(1,    rgb(255,173,225))
  );
  background-image: -moz-linear-gradient(
    center left,
    rgb(255,143,212) 41%,
    rgb(255,153,216) 56%,
    rgb(255,173,225) 100%
  );
}

/* Styles for animated states */
span.css-emoticon.un-transformed-emoticon, span.css-emoticon.animated-emoticon:hover {
    /* font-size: inherit;
    font-weight: inherit;
    vertical-align: inherit;
    line-height: inherit;
    font-family: inherit; */
    letter-spacing: inherit;
    color: inherit;
    overflow: visible;
    transform: rotate(0deg);
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    background: none;
    background-image: none;
    box-shadow: none;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    border-color: transparent;
}

span.css-emoticon.nintendo-controller {
  font-size: .8em;
  height: 1.2em;
  line-height: 1em;
  width: 2.7em;
  vertical-align: bottom;
  border-radius: 0;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  background: -webkit-gradient(
      linear,
      left bottom,
      left top,
      color-stop(0.09, rgb(116,121,140)),
      color-stop(0.55, rgb(165,170,189))
  );
  background: -moz-linear-gradient(
      center bottom,
      rgb(116,121,140) 9%,
      rgb(165,170,189) 55%
  );
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="comment">
  Hi, this is a great plugin! :-)
</div>
&#13;
&#13;
&#13;

试试这个

答案 3 :(得分:0)

如何使用https://afeld.github.io/emoji-css/

代码示例:

function mreplace(replacements, str) {
  for (let [x, y] of replacements) {
    str = str.replace(x, s => `<i class="em em-${y}"></i>`);
  }
  return str;
}
let output = document.querySelector('#output');
let input = 'I want to be always happy, but never confused!';
let result = mreplace([
  [/happy/ig, 'blush'],
  [/confused/ig, "confused"]
], input);

output.innerHTML = result;
console.log(result);
<link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">

<p id="output"></p>