0

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.

2
  • 1
    Writing var html = '/example.html' creates a string rather than retrieving the html text from a file. You will need to use $.ajax for the latter. Commented Feb 25, 2017 at 16:55
  • why don't you use template engines such as ejs, jade Commented Feb 25, 2017 at 16:57

1 Answer 1

1

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!'))
    }
  })

})

Sign up to request clarification or add additional context in comments.

1 Comment

Thank, you! This works, but looks more like workaround. I am new to JS, so I can be wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.