Search code examples
javascriptinserthtml

Assign HTML snippet to JS variable


I have an example.html file:

<span>
{{test}}
</span>

And a main.js file:

$( "button#test" ).click(function(event) {

        var html = '/example.html';

        //Replaceing {{test}} in example.html with 'Hello, World!' string
        var insertProperty = function (string, propName, propValue) {
            var propToReplace = "{{" + propName + "}}";
            string = string
                .replace(new RegExp(propToReplace, "g"), propValue);
            return string;
        }
        var replacedhtml = insertProperty(html,"test", 'Hello, World!');

        return console.log(replacedhtml);
    });

What I currently get in log:

/example.html

What I expect:

<span>
Hello, World!
</span>

And there should be a more elegant way to insert property than my insertProperty function.


Solution

  • Writing var html = '/example.html' creates a string rather than retrieving the html text from a file. Instead, use $.ajax to asynchronously request the file and do something with its text.

    $('#test').click(function () {
    
      $.ajax({
        url: '/example.html',
        success: function (html) {
    
          //Replacing {{test}} in example.html with 'Hello, World!' string
          function insertProperty (string, propName, propValue) {
            return string.replace(new RegExp('{{' + propName + '}}', 'g'), propValue)
          }
    
          console.log(insertProperty(html, 'test', 'Hello, World!'))
        }
      })
    
    })