How to replace script tag data with jQuery?

3

I am trying to replace a certain value inside a HTML parseado , using the following function I can replace values that are inside tags inputs, css and etc:

$('input[value="/services/CouponTemplate.mvc/GetCoupon"]').attr('value', function(_, href){
    return "https://meusite.com?url=https://siteremoto.com" + href;
});

But now I need to replace an address that is inside the <script type="text/javascript"> tag. Here's how:

<script type="text/javascript">var inPlayPreferences={"MarketOrder":,"InPlayAppServiceName":"/services/InPlayApp.mvc/"};</script>

I need to replace /services/InPlayApp.mvc/ , I get through PHP with str_replace , but I would like to know if I can do the same using jQuery. I tried to repeat the procedure by changing input by script but it did not work, I am a beginner in Javascript world. Is there anything similar to str_replace of PHP in jQuery?

    
asked by anonymous 12.05.2015 / 08:21

1 answer

2

You can assign an identifier for this script tag, so it is easier to find it, eg

<script id='scriptQueSeraAlterado' type='text/javascript'></script>

With jQuery:

$(function(){
  
  var script = $('#theScript'); // alvo
  var content = 'var bar = 10;'; // conteúdo que será inserido dentro da tag
  
  $('#changeScriptContent').on('click', function(){
    alert('Antes de alterar:\n' + script.get(0).outerHTML);
    script.html(content); // :)
    alert('Depois de alterar:\n' + script.get(0).outerHTML);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><scriptid='theScript'>varfoo=2;</script><buttonid='changeScriptContent'>Alterar</button>

OnlywithJavascript:

var button = document.getElementById('changeScriptContent'), // botão que altera o conteúdo
    script = document.getElementById('theScript'), // alvo
    content = 'var bar = 10;'; // conteúdo que será inserido

button.addEventListener('click', function(){
    alert("Antes de alterar:\n" + script.outerHTML);
    script.innerHTML = content; // :)
    alert("Depois de alterar:\n" + script.outerHTML);
});
<script id='theScript'>
    var foo = 2;
</script>

<button id='changeScriptContent'>Alterar</button>
    
12.05.2015 / 09:02