Drupalize image paths
by timmah
HTML
<a href="/file/abc.pdf" class="nounderline">NCIS Charter</a>
<a href="abc.doc" class="nounderline">Reconciliation at NCIS</a>
<a href="http://www.mysite.com/file/file1.jpg" class="nounderline">Related programs & sites</a>
JavaScript
/* This script replaces file paths with Drupal equivalents,
* assuming files are stored under /sites/default/files
*
* To use, paste the page SOURCE (Ctrl + U) - not the DOM - into the box above,
* and click 'Run' in the top right corner.
*
* The HTML you want is everying inside <div id="content">, starting with:
*
* <!-- START MAIN PAGE CONTENT -->
*
* and ending at:
*
* <!-- END MAIN PAGE CONTENT -->
*
*/
// First, strip any unwanted elements
var needsNewPaths = $('body'),
exts = ["bmp", "doc", "docx", "flv", "gif", "jpg", "jpeg", "mp3", "mp4", "mpg", "mpeg", "png", "pdf", "ppt", "pptx", "rtf", "wma", "zip"],
unwantedBits = $('h1, a.scrollup');
unwantedBits.remove();
for (var i = 0; i < exts.length; i++) {
needsNewPaths = needsNewPaths.add($('a[href$=".' + exts[i] + '"]'));
console.log('needsNewPaths.length: ' + needsNewPaths.length)
}
// Check each image, replace file path
needsNewPaths.each(function(i, e) {
console.log(typeof(needsNewPaths[i]));
var $this = $(this),
$attr = function() {
// If the element is an image...
if ($this.is('img')) {
return 'src'
// else assume it is an anchor. Add more conditions if more element types are added to 'needsNewPaths'
} else {
return 'href'
}
}
// Split attribute path
$parts = $this.attr($attr()).split('/'),
// Get the file, which will be the last item in our Split array
$file = $parts[$parts.length - 1];
/* // Test values here
console.log('$parts: ' + $parts);
console.log('$file: ' + $file);
*/
// Assign the new paths
$this.attr($attr(), '/sites/default/files/' + $file);
});