Home > front end >  How can I repair my HTML code to convert letters to numbers?
How can I repair my HTML code to convert letters to numbers?

Time:05-05

I have a code like this:

    <!DOCTYPE html>
    <html>
      <head>
        <script>
          function replace(){
            var text = document.getElementById("textarea").value;
            var a = text.replace("a", "11");
            var b = text.replace("b", "12");
            var c = text.replace("c", "13");
            document.getElementById("textarea").value = abc;
          }
        </script>
      </head>
      <body>
        <textarea rows="4" cols="50" id="textarea"></textarea>
        <button id="button" onclick="replace();">replace</button>
      </body>
    </html>

I'd like to replace letters with numbers, but I don't know how can I repair this script - only first "var" works or it doesn't work at all. I think the problem is here:

document.getElementById("textarea").value = abc;

Thank you.

CodePudding user response:

This is a correct way, you need to

<!DOCTYPE html>
<html>
  <head>
    <script>
      function replace(){
        var text = document.getElementById("textarea").value;
        text = text.replace("a", "11");
        text = text.replace("b", "12");
        text = text.replace("c", "13");
        document.getElementById("textarea").value = text;
      }
    </script>
  </head>
  <body>
    <textarea rows="4" cols="50" id="textarea"></textarea>
    <button id="button" onclick="replace();">replace</button>
  </body>
</html>

  1. replace does not change the text
  2. "concatenation" abc didn't make too much sense, but you rather wanted to apply in a sequence 3 transformations

and here is (for a historical reasons :) ) an external playground for you: https://jsfiddle.net/mPrinC/ds9482zn/3/

  •  Tags:  
  • html
  • Related