如何在脚本源中替换url

时间:2016-04-14 09:30:47

标签: javascript jquery html regex scripting

有一个网址

  

/Kentico9/CMSPages/GetResource.ashx

在以下脚本中,

  <script src="/Kentico9/CMSPages/GetResource.ashx?scriptfile=%7e%2fCMSScripts%2fRequireJS%2frequire.js" type="text/javascript"></script>
<script src="/Kentico9/CMSPages/GetResource.ashx?scriptfile=%7e%2fCMSScripts%2fRequireJS%2fconfig.js&amp;resolvemacros=1" type="text/javascript"></script>
<script src="/Kentico9/CMSPages/GetResource.ashx?scriptfile=%7e%2fCMSScripts%2fcms.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if ((window.originalPostback == null) && (window.__doPostBack != null)) { window.originalPostback = __doPostBack; __doPostBack = __doPostBackWithCheck; }

//]]>
</script>
<script src="/Kentico9/ScriptResource.axd?d=_9yHV47QJb18THQ6kRwtMTYWP8AyLTDDz_ezsjVynWQhicLV_U3iBRnjAic5MX-xDgyPX48_xtLVYXhKOv2UCJKAoTTMC4wGhtJzijblJUqnor1iJ4U59KPu7436hU-u0&amp;t=7c776dc1" type="text/javascript"></script>
<script src="/Kentico9/ScriptResource.axd?d=zf3zdXaB_cJmg3ZI845HWFeB9wwz6hDKzOk9u8r8LRzjBXOxGqGc8ov1CG1yunKlRYOyRHSZ9KBtNMB3nu1nMQXXiYklnIFMhWV0Xj3pkcNu0JnN6rQtu7_ee21y6R8Tp2tmpXsVH8ZTIabIz8lDAA2&amp;t=7c776dc1" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var CMS = CMS || {};
CMS.Application = {
"isRTL": "false",
"isDebuggingEnabled": true,
"applicationUrl": "/Kentico9/",
"imagesUrl": "/Kentico9/CMSPages/GetResource.ashx?image=%5bImages.zip%5d%2f",
"isDialog": false
};

我需要更改此网址

/Kentico9/CMSPages/GetResource.ashx 

http://localhost/Kentico9/CMSPages/GetResource.ashx

我尝试使用以下脚本进行替换,但这不起作用。

var res = "entire html source shown above";
res.replace('/Kentico9/', 'http://localhost/Kentico9/');

我如何使这个工作?

3 个答案:

答案 0 :(得分:1)

专门针对imageURL

进行尝试
res.replace('"imagesUrl": "/Kentico9/', '"imagesUrl": "http://localhost/Kentico9/');

答案 1 :(得分:1)

两件事:

  1. replace 返回新字符串。

  2. 当您将字符串作为第一个参数传递时,它仅替换第一个实例,而不是所有实例。要替换所有,您需要一个带有g标记的正则表达式。

  3. 所以:

    res = res.replace(/\/Kentico9\/CMSPages\/GetResource\.ashx/g, 'http://localhost/Kentico9/CMSPages/GetResource.ashx');
    //  ^-- assign    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^
    //                regex                                    global
    

    请注意,正则表达式中的/.是转义的,否则它们在正则表达式中具有特殊含义。

答案 2 :(得分:1)

使用此

var remove = "/Kentico9/CMSPages/GetResource.ashx";
var newLink = "http://localhost/Kentico9/CMSPages/GetResource.ashx";
$('script').each(function(){
  var link = $(this).attr('src');
  $(this).attr('src', link.replace(remove, newLink));
})