-1

I am using the Chuck Norris joke generator API. I was wondering if it would be possible in this situation to change part of the string returned 'Chuck Norris' to something else. I've tried a few different ideas and I'm really stuck.

E.g instead of 'Chuck Norris built the hospital he was born in.' the API could return 'Dalai Lama built the hospital he was born in.' instead.

document.querySelector('.get-jokes').addEventListener('click', getJokes);

function getJokes(e) {
  const number = document.querySelector('input[type="number"]').value;

  const xhr = new XMLHttpRequest();

  xhr.open('GET', `http://api.icndb.com/jokes/random/${number}`, true);

  xhr.onload = function() {
    if (this.status === 200) {
      const response = JSON.parse(this.responseText);

      console.log(response);
      let output = '';

      if (response.type === 'success') {
        response.value.forEach(function(getjoke) {
          output += `<li>${getjoke.joke}</li>`;
        });
      } else {
        output += '<li>Something went wrong</li>';
      }

      document.querySelector('.jokes').innerHTML = output;
    }
  };

  xhr.send();

  e.preventDefault();
}
<div class="container">
  <h2>Chuck Norris Joke Generator</h2>
  <form>
    <div>
      <label for="number">Number of jokes</label>
      <input type="number" id="number">
    </div>
    <div>
      <button class="get-jokes">Get Jokes</button>
    </div>
  </form>
  <ul class="jokes"></ul>
</div>
Josh
  • 110
  • 1
  • 7
  • 1
    Does this answer your question? [How to replace all occurrences of a string?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string) – Reyno Oct 08 '20 at 12:30
  • 1
    `output += \`
  • ${getjoke.joke.replace(/Chuck Norris/g, "Dalai Lama")}
  • \`;` –  Oct 08 '20 at 12:31
  • Chris, that's perfect, thank you! – Josh Oct 08 '20 at 12:35
  • Here's a rewrite using modern code: https://jsfiddle.net/sbmf0qv7/ –  Oct 08 '20 at 12:40
  • Would there be a way to change multiple parts of the string using that method? – Josh Oct 08 '20 at 12:49