2015-12-24 55 views
-6

替換字符我有一個​​像如何在JavaScript

var content = '<img id="product-collection-image-515" src="http://www.dressbd.com/media/catalog/product/cache/1/small_image/300x300/9df78eab33525d08d6e5fb8d27136e95/r/u/shirt.jpg" alt="Shirt"></img>'; 

一個字符串,我想改變它像下面。

var content = '<img id="product-collection-image-515" src="https://www.dressbd.com/media/catalog/product/cache/1/small_image/300x300/9df78eab33525d08d6e5fb8d27136e95/r/u/shirt.jpg" alt="Shirt"></img>'; 

我想用'https'替換'http'使用JavaScript。我用.replace(),但它不工作。

我該怎麼做?由於

+4

在你的問題中你提到你使用了'。替換()'功能,這並沒有工作,但你忘了告訴我們你的代碼。所以很難說出你可能做錯了什麼。 –

+0

您可以提供整個代碼來檢查,因爲replace()通常用於此任務 – pTi

+0

不要使用regexp來修改HTML。相反,如果HTML位於DOM中,請修改'img'元素的'src'屬性。 –

回答

0

我通常使用.split() 例如.split("//")

var p = content.split("//"); 
p[0] += "s"; 
var result = p[0] + p[1]; 
2

這樣你是什麼意思?作品replace()應該

var content = '<img id="product-collection-image-515" src="http://www.dressbd.com/media/catalog/product/cache/1/small_image/300x300/9df78eab33525d08d6e5fb8d27136e95/r/u/shirt.jpg" alt="Shirt"></img>'; 
 

 
var newContent = content.replace('http','https'); 
 

 
alert(newContent)

+0

我試過了,但它不起作用。 –

+2

單擊上面的按鈕「運行代碼片段」,你會看到一個警告與URL使用「https」 - 如果它不適合你,那麼其他東西是錯誤的 –

+2

@ Erik-JanWestendorp請停止建議編輯,其中添加換行字符串文字。這在JS中是無效的。我回滾了編輯。 – Oriol

0

試試這個

var str = "Hi William How are You?", 
 
    res = str.replace("William", "Anderson"); 
 
alert(res);

結果將是:

Hi Anderson How are You? 
+0

我試過了,但它不起作用。 –

0

如果替換函數不適用於您,可能是您沒有將返回值分配給新變量。

E.g.你不能只是這樣做:

content.replace('http','https') 

由於該函數返回結果和實際上本身並沒有改變「內容」的字符串。

相反,你需要這樣做:

var newvar = content.replace('http','https'); 

然而,你可能不需要任何代碼。

在urls前面使用//將指示瀏覽器使用與當前頁面相同的協議。例如,如果從

https://example.com/mypage 

此鏈接

//google.com/somestuff.js 

請求爲

https://google.com/somestuff.js 

,而如果你是一個普通的HTTP站點時,鏈接將被要求作爲

http://google.com/somestuff.js 
觀看

如果您嘗試加載混音編輯內容(http和https)到一個頁面中,瀏覽器會抱怨安全問題,所以它總是最好使用//格式。