2014-02-11 90 views
0

我知道這是一個非常基本的問題,原諒我甚至問,但我似乎無法爲我的生活做好準備。用JQuery替換url中的字符串

我正在使用jQuery從一個圖像src中獲取URL並將其加載到另一個圖像src中,我工作正常。不過,我需要用800x600之類的東西來替換url的100x75部分,這樣才能拉出更大的圖片。

我該怎麼做?

下面是一個例子: 說我在抓住與jQuery圖像源的URL,它看起來是這樣的:http://example.com/images/Something_cool-100x75.png 我需要它看起來像這樣:http://example.com/images/Something_cool-800x600.png

jQuery(document).ready(function($) { 
    // this will pull the image I need 
    var get_image = $('img.attachment-shop_thumbnail').attr('src'); 

    //this will assign the image I pulled above to where I need it to go but I need to replace the 100x75 in the filename to 800x600 
    $("#sale_img").attr("src", get_image); 
}); 

所以,如果你提供了可能的答案你能告訴我它是如何工作的,因爲我還需要改變.png格式以JPG格式對他們中的一些以及..只是不知道如何

+0

具有該代碼和jQuery標籤是不公平的,它可以縮小到簡單的如何將stringX轉換爲stringY – ajax333221

回答

1

簡單的JavaScript替代可以做你的工作

var get_image = $('img.attachment-shop_thumbnail').attr('src'); 
get_image = get_image.replace("100x75","800x600"); 

以同樣的方式使用它的替代巴紐以JPG格式。所以,此番

var get_image = $('img.attachment-shop_thumbnail').attr('src').replace("100x75","800x600")..replace(".png",".jpg"); 
1
var old = "http://example.com/images/Something_cool-100x75.png"; 
var new = old.replace("100x75","800x600"); 
new = new.replace(".png",".jpg"); 
alert(new); 

警報"http://example.com/images/Something_cool-800x600.jpg"

1

試試這個

var get_image = $('img.attachment-shop_thumbnail').attr('src').replace('100x75', '800x600'); 
2

你可以使用正則表達式:

string.replace(/\d+x\d+/, '800x800') 

基本上,它找到一個數字(\d)1或更多的時間(+),其次是一個「x」和一個或多個時間查找另一個數字。

它改變它爲你說的價值。

作爲.JPG,你仍然可以使用正則表達式:string.replace(/\.png$/, '.jpg')

小提琴:http://jsfiddle.net/8mYYZ/

0

我想一個更好的實現是有一個單獨的CSS類爲每個圖像(除非有很多)。不必擔心圖像源的字符串操作,您可以簡單地更改該類。