Jonathan
Jonathan

Reputation: 683

Replace numbers within a string

I currently have this code.

var result = {
    productName: $(".product-details .product-title").text().trim(),
    description: $(".product-details .product-description p").text().trim(),
    price: $(".product-details .price-lockup meta[itemprop='lowPrice']").attr("content"),
    imageUrls: []
};

$('.image-cache img[src*="?fit=fill&bg=fff&fm=jpg&q=60&w=380&h=583"]').each( function() {
    var url = $(this).attr("src");
    result.imageUrls.push(url);
});

What I'm wanting to do is replace '380' and '583' within the src string with 860 and 1318. I've read a few questions here but they don't actually deal with finding and replacing them with other numbers.

Any help would be brilliant!

Upvotes: 0

Views: 52

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 99071

You can use replace()

var url = $(this).attr("src").replace("380","860").replace("583","1318");

Complete function:

var result = {
    productName: $(".product-details .product-title").text().trim(),
    description: $(".product-details .product-description p").text().trim(),
    price: $(".product-details .price-lockup meta[itemprop='lowPrice']").attr("content"),
    imageUrls: []
};

$('.image-cache img[src*="?fit=fill&bg=fff&fm=jpg&q=60&w=380&h=583"]').each( function() {
    var url = $(this).attr("src").replace("380","860").replace("583","1318");
    result.imageUrls.push(url);
});

Upvotes: 1

Andrew Mairose
Andrew Mairose

Reputation: 11005

Just use the String replace() method.

url = url.replace('380', '860');
url = url.replace('583', '1318');

Upvotes: 0

Related Questions