homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

Modifying all data-original text

5+ Year Member

Msg#: 4673031 posted 10:56 am on May 21, 2014 (gmt 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" />



WebmasterWorld Senior Member fotiman us a WebmasterWorld Top Contributor of All Time 5+ Year Member

Msg#: 4673031 posted 2:45 pm on May 21, 2014 (gmt 0)

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('.'),
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.

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved