Welcome to WebmasterWorld Guest from 54.146.201.80

Forum Moderators: open

Message Too Old, No Replies

Modifying all data-original text

     
10:56 am on May 21, 2014 (gmt 0)

Full Member

5+ Year Member Top Contributors Of The Month

joined:Sept 30, 2009
posts:222
votes: 0


I'm having a hard time inserting "@2" before the file extension of all data-original attributes on a page. Is there a simple way of doing this? If it helps, I'm using jQuery.

<div data-original="/XXXXX.jpg" /> to <div data-original="/XXXXX@2.jpg" />
2:45 pm on May 21, 2014 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 4965
votes: 10


Here's a quick and dirty example:

// Find all elements with data-original attribute
$('[data-original]').each(function () {
var $this = $(this),
origVal = $this.data('original'),
idx = origVal.lastIndexOf('.'),
beginning = origVal.substring(0, idx),
ending = origVal.substring(idx),
newVal = beginning + (idx >= 0? '@2': '') + ending;
$this.data('original', newVal);
});


This method assumes the last "." in the string is the beginning of the file extension and uses string methods (lastIndexOf, substring) to split the string into parts, and then concatenate the results. There are probably more efficient ways to do this using split and join methods or using a RegEx.

Here's another example using split and join:

$('[data-original]').each(function () {
var $this = $(this),
origVal = $this.data('original'),
arrVals = origVal.split('.'),
newVal;
if (arrVals.length > 1) {
arrVals[arrVals.length - 2] = arrVals[arrVals.length - 2] + '@2';
newVal = arrVals.join('.');
$this.data('original', newVal);
}
});


I haven't done any performance testing on these. I find the first example to be easier to look at and quickly understand what it's doing, but your mileage may vary. :)

Hope that helps.