Ahmed Elmahdy Ahmed Elmahdy - 1 month ago 8
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:

data.consumer_key
data.consumer_secret


Question



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

Example:

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


However, I want it to be dynamic. Catch all data returned and replace the
{{data_key}}
automatically. Can that be done or not? I mean, without precisely telling jquery to replace
{{consumer_key}}
but
{{replace_anything}}
with
data.replace_anything
. 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

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(
      $('#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>

Comments