By user3592901


2019-04-15 11:00:18 8 Comments

I have written this code which I thought was correct, but although it runs without error, nothing is replaced. Also I am not sure what event I should use to execute the code.

The test a simple template for a landing page. The tokens passed in on the url will be used to replace tags or tokens in the template.

<!DOCTYPE html>

<html>

<head>
  <title>TODO supply a title</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script>
    // gets passed variables frm the url
    function getQueryVar(str) {
      return 'Newtext'; // JUST  SCAFFOLD FOR TESTING
    }

    function searchReplace() {
      /**/
      var t = 0;
      var tags = Array('keyword', 'locale', 'advert_ID');

      if (document.readyState === 'complete') {
        var str = document.body.innerText;

        for (t = 0; t < tags.length; t++) {
          //replace in str every instance of the tag with the correct value

          if (tags[t].length > 0) {
            var sToken = '{ltoken=' + tags[t] + '}';
            var sReplace = getQueryVar(tags[t]);
            str.replace(sToken, sReplace);
          } else {
            var sToken = '{ltoken=' + tags[t] + '}'
            var sReplace = '';
            str.replace(sToken, sReplace);
            //str.replace(/sToken/g,sReplace); //all instances

          }
        }
        document.body.innerText = str;
      }


    }
  </script>
</head>

<body>
  <H1> THE HEADING ONE {ltoken=keyword}</H1>
  <H2> THE HEADING TWO</H2>
  <H3> THE HEADING THREE</H3>
  <P>I AM A PARAGRAPH {ltoken=keyword}</P>

  <div>TODO write content</div>

  <input type="button" onclick="searchReplace('keyword')">
</body>

</html>

So when the documment has finished loading I want to execute this code and it will replace {ltoken=keyword} withe value for keyword returned by getQueryVar. Currently it replaces nothing, but raises no errors

2 comments

@Kamil Kiełczewski 2019-04-15 11:08:29

Use innerHTML instead innerText and instead your for-loop try

tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)))

<!DOCTYPE html>

    <html>
           <head>
          <title>TODO supply a title</title>
           <meta charset="UTF-8">
           <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <script>
     // gets passed variables frm the url
   function getQueryVar(str)
   {
               return'Newtext';// JUST  SCAFFOLD FOR TESTING
   }        

   function searchReplace() {
   /**/
   var t=0;
   var tags =Array('keyword','locale','advert_ID');

   if (document.readyState==='complete'){
   var str = document.body.innerHTML;
       tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)));
       //tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ tags[t]+'}', 'g'), getQueryVar(tags[t])));

       
   document.body.innerHTML=str;
   }


   }

   </script>
       </head>
       <body   >
           <H1>  THE HEADING ONE {ltoken=keyword}</H1>
            <H2>  THE HEADING TWO</H2>   
            <H3>  THE HEADING THREE</H3> 
            <P>I AM A PARAGRAPH {ltoken=keyword}</P>

           <div>TODO write content</div>

           <input type ="button" onclick="searchReplace('keyword')" value="Clicke ME">
       </body>
   </html>

@user3592901 2019-04-15 12:08:40

This code is just hanging, don't know why Your line looks so much nicer than mine, I learned a long time ago and also out of practice. It probably shows

@Kamil Kiełczewski 2019-04-15 12:19:22

Hanging? On snippet it works...

@user3592901 2019-04-15 13:01:20

I picked out your line of replacement code and fitted into mine. It worked a treat and replaces all instances. Thanks a load for that I up voted you but sadly my rep is not strong enough for it to show

@Kamil Kiełczewski 2019-04-15 13:53:46

@user3592901 you click on gray big "check" button (not triangle) on left side this answer to accept it

@Adriani6 2019-04-15 11:05:06

Your problem is the fact you don't reassign the replacement of the string back to it's parent.

str.replace(sToken,sReplace);

should be

str = str.replace(sToken,sReplace);

The .replace method returns the modified string, it does not perform action on the variable itself.

@user3592901 2019-04-15 12:09:08

Makes a load of sense, will test that

@user3592901 2019-04-15 12:13:32

Ok that fixed one problem. Thanks so much for spotting my childish error. I still have two problems to solve 1. My replace only replaces one instance, I don't know how to use the /g flag with two variables if I were replacing a string, I believe the syntax is: str=str.replace(/'johhny'/g,sReplace); I tried this: str=str.replace(/sToken/g,sReplace); No luck 2. Is body.onload a safe way to trigger this function?

@user3592901 2019-04-15 13:01:32

I up voted you but sadly my rep is not strong enough for it to show

Related Questions

Sponsored Content

78 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5650946 View
  • 7025 Score
  • 78 Answer
  • Tags:   javascript arrays

3 Answered Questions

38 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

50 Answered Questions

[SOLVED] How to replace all occurrences of a string in JavaScript

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

9 Answered Questions

[SOLVED] Why does HTML think “chucknorris” is a color?

54 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

26 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

Sponsored Content