javascript - 替换 html 元素的字符串

标签 javascript jquery html string twitter-bootstrap

我正在研究随机选择的数组字符串的控制流。如果字符串包含我的测试用例之一,它将转换为“???”。为了增强演示效果,我想将其更改为 Bootstrap 字形图标。我目前正在使用 .replace() 将字符串修改为不同的字符串:有没有办法将字符串修改为 span 元素?

我一直在查看 .replace() 和 other 的文档关于 similar 的问题主题,但到目前为止我还无法应用解决方案。

function setSentence() {
  // Return random int between min (included) and max (excluded)
  function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min;
  }

  const sentenceList = ["El mundo era tan reciente, que muchas cosas carecían de nombre, y para mencionarlas había que señalarías con el dedo.", "Melquíades, que era un hombre honrado, le previno: «Para eso no sirve.»", "Pero José Arcadio Buendía no creía en aquel tiempo en la honradez de los gitanos, así que cambió su mulo y una partida de chivos por los dos lingotes imantados.", "Úrsula Iguarán, su mujer, que contaba con aquellos animales para ensanchar el desmedrado patrimonio doméstico, no consiguió disuadirlo.", "«Muy pronto ha de sobrarnos oro para empedrar la casa», replicó su marido."];

  var sentence = sentenceList[getRandomInt(0, sentenceList.length)];
  var $sentence = $("#test-sentence");
  var testSentence = sentence;


  // instead of "??? " I would like to replace the identified text for <span class="glyphicon glyphicon-question-sign"></span> plus a space

  if (testSentence.includes("por ") || testSentence.includes("Por ")) {
    if (testSentence.includes("por ")) {
      testSentence = testSentence.replace("por ", "??? ");
    } else {
      testSentence = testSentence.replace("Por ", "??? ");
    }
  } else {
    if (testSentence.includes("para ")) {
      testSentence = testSentence.replace("para ", "??? ");
    } else {
      testSentence = testSentence.replace("Para ", "??? ");
    }
  }

  $sentence.text(testSentence);
}

setSentence();

该 html 包含:

<p><span id="test-sentence"></span></p>

最佳答案

将字符串替换为跨度文本,并使用 .html() ,jQuery会将字符串转换为html内容:

function setSentence() {
  // Return random int between min (included) and max (excluded)
  function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min;
  }

  const sentenceList = ["El mundo era tan reciente, que muchas cosas carecían de nombre, y para mencionarlas había que señalarías con el dedo.", "Melquíades, que era un hombre honrado, le previno: «Para eso no sirve.»", "Pero José Arcadio Buendía no creía en aquel tiempo en la honradez de los gitanos, así que cambió su mulo y una partida de chivos por los dos lingotes imantados.", "Úrsula Iguarán, su mujer, que contaba con aquellos animales para ensanchar el desmedrado patrimonio doméstico, no consiguió disuadirlo.", "«Muy pronto ha de sobrarnos oro para empedrar la casa», replicó su marido."];

  var sentence = sentenceList[getRandomInt(0, sentenceList.length)];
  var $sentence = $("#test-sentence");
  var testSentence = sentence;


  // instead of "??? " I would like to replace the identified text for <span class="glyphicon glyphicon-question-sign"></span> plus a space

  if (testSentence.match(/por\b/i)) { // find por at end of words, ignore case
    testSentence = '<span>' + testSentence.replace(/\bpor\b/ig, "<span class=\"glyphicon glyphicon-question-sign\"></span>") + '</span>';
  } else if (testSentence.match(/para\b/i)) {  // find pata at end of words, ignore case
    testSentence = '<span>' + testSentence.replace("para ", "<span class=\"glyphicon glyphicon-question-sign\"></span>") + '</span>';
  }

  $sentence.html(testSentence);
}

setSentence();
.glyphicon::before {
  content: '?demo?'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="test-sentence"></div>

关于javascript - 替换 html 元素的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47188911/

相关文章:

javascript - 如何在不使用 flash 的情况下将文本复制到剪贴板?

javascript - 如何获取单击的按钮的值 Javascript 或 Jquery

javascript - 如何使用带有 Django 模板标签的 amp CSS 星级评分?

html - 上传到托管网站时代码不起作用

javascript - 向现有 QT 应用程序添加 javascript 支持

javascript - AngularJS ngModelController 基本问题

jquery - 引用 DOM jQuery DOM 对象时使用变量

html - 根据窗口宽度自动调整 div 高度

javascript - AngularJS 与 RequireJS 标签显示 breifly

jquery - Twitter Bootstrap : modal fade