简体   繁体   中英

Javascript String#replaceAll only working on one instance

I have a body of text and there are some string within square brackets like [value] I am trying to run a function that lets the user enter a value for each [...]. I have the most of it working but when I console.log the changed body, only some of the values change. Some of them have html tags like [<strong>Hello</strong>] and they are not being changed. I'm just not sure how to overcome it.

let data = $('#elm1').val();
  console.log(data);
  let newData;

  function getWords() {
    let words = data.match(/[^[\]]+(?=])/g);

    console.log(words);

    words.forEach(function(word) {
      console.log(word);

      let input = prompt("Enter value to replace: "+word);

      newData = data.replaceAll("["+word+"]", input);
    });

    console.log(newData);
  }

The problem was every time the forEach was ran it was just updating one word and displaying the body with the last word that was updated.

I fixed this by adding data = newData when the iteration of the loop happened to save the previous change before moving onto the next.

let data = $('#elm1').val();
  console.log(data);
  let newData;

  function getWords() {
    let words = data.match(/[^[\]]+(?=])/g);

    console.log(words);

    words.forEach(function(word) {
      console.log(word);

      let input = prompt("Enter value to replace: "+word);

      newData = data.replaceAll("["+word+"]", input);
      data = newData; //Added this
    });

    console.log(newData);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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