Ahmed Elmahdy Ahmed Elmahdy - 1 year ago 89
jQuery Question

Can I auto replace specific strings by returned data keys in jQuery?

I use jQuery.ajax to get some variables/response from the server side.

The returned data is json object like this:



Can I automatically replace strings found in a specific container, e.g.
to replace the matching formula for the returned data automatically.


mystring.replace( '{{consumer_key}}', data.consumer_key );

However, I want it to be dynamic. Catch all data returned and replace the
automatically. Can that be done or not? I mean, without precisely telling jquery to replace
. Hope my point is clear.

Currently this works but I need it for like 10 data keys, so I am looking for an automatic preg replace solution. any idea?

$( '#api-keys-options' ).html( $( '#api-keys-options' ).html().replace( '{{consumer_key}}', data.consumer_key ) );

Many thanks

Answer Source

If your ajax call returns an object, lets call it data, and that data object has several properties that you want to access, you can loop over them using:

for (var prop in data) {
    console.log("property name: " + prop + ", property value: " + data[prop]);

In your case, you would want to replace the string '{{' + prop +'}}' in the value of data[prop] (based on the above code example).

Here is a better working snippet:

data = {'name1': 'value1', 'name2': 'value2'}
$('#btn1').click(function() {
  for (var prop in data) {
    console.log("property name: " + prop + ", property value: " + data[prop]);
      $('#d1').html().replace('{{'+prop+'}}', data[prop]));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d1">This is some text with {{name1}} variables and some {{name2}} variables</div>
<br />
<button id="btn1">Replace</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download