简体   繁体   English

加载随机数组字符串并替换一个单词

[英]load a random array string and replace one word

I have an array of Spanish sentences, all of which include one instance of "por" or "para" (capitalized or not). 我有一系列西班牙语句子,所有句子都包含一个“ por”或“ para”实例(是否大写)。 I'm trying to load one random sentence on the browser, replacing the test case of por/para for question marks ("???"). 我正在尝试在浏览器中加载一个随机句子,以por / para的测试用例替换问号(“ ???”)。 Thus far it's loading the original sentence without applying the character operation. 到目前为止,它是在不应用字符操作的情况下加载原始句子的。

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.»", "Úrsula Iguarán, su mujer, que contaba con aquellos animales para ensanchar el desmedrado patrimonio doméstico, no consiguió disuadirlo.",
  ];

  var sentence = sentenceList[getRandomInt(0, sentenceList.length)];

  var $sentence = $("#test-sentence");

  var testSentence = sentence;

  if (testSentence.includes("por ") || testSentence.includes("Por ")) {
    if (testSentence.includes("por ")) {
      testSentence.replace("por ", "???");
    } else {
      testSentence.replace("Por ", "???");
    }
  } else {
    if (testSentence.includes("para ")) {
      testSentence.replace("para ", "???");
    } else {
      testSentence.replace("Para ", "???");
    }
  }
  $sentence.text(testSentence);
}
setSentence();

And the html: 和html:

<div class="container">  
  <p><span id="test-sentence"></span></p>    
</div>

Per MDN : 每个MDN

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. replace()方法返回一个新字符串,该字符串具有部分或全部模式匹配项,并由替换项替换。

So you need to do an assignment each time you want to modify your string with .replace() : 因此,每次您想使用.replace()修改字符串时,都需要进行分配:

testSentence = testSentence.replace("para ", "???");

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

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