Skip to content

Instantly share code, notes, and snippets.

@mcsheffrey
Created February 4, 2012 04:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcsheffrey/1735249 to your computer and use it in GitHub Desktop.
Save mcsheffrey/1735249 to your computer and use it in GitHub Desktop.
Find and replace HTML with arbitrary text using Node
var jsdom = require('jsdom'),
fs = require('fs'),
allLinks = JSON.parse(fs.readFileSync('/Users/lkarrys/melt-git/IAC/bundles/common/src/main/resources/site/lib/helpers/data/link-like-data.nav', 'utf-8')),
file = process.argv[2];
if (!file) throw('it');
fs.readFile(file, 'utf-8', function(err, data) {
jsdom.env({html: '<html><body>'+data+'</body></html>', scripts: ['http://code.jquery.com/jquery-1.7.min.js']}, function (err, window) {
var $ = window.jQuery, $body = $('body'), linkLikes = $body.find('span.link-likes');
// Find each link-like element
linkLikes.each(function() {
var $this = $(this),
$parent = $(this).parent(),
linkTitle = $parent.find('a.third-party').html().trim(),
linkId = $this.html().replace(/\{/g, '').replace(/\}/g, '').trim(),
linkData = allLinks[linkId],
defaultTitle = linkData.title[0],
replaceString = '{{linkLike "'+linkId+'" ';
if (!linkData) {
console.log('____ERROR: '+linkId+' not found from '+file);
} else {
console.log(file+ " --|-- " +linkId)
// If our link-like element doesnt have the default title
if (linkTitle !== defaultTitle) {
var possibleTitles = allLinks[linkId].title, replaceTitle = '';
// Do we have the title stored in the titles array?
for (var i = 1, m = possibleTitles.length; i < m; i++) {
if (possibleTitles[i] === linkTitle) {
replaceTitle = i;
break;
}
}
// If not, then pass in string of current title
if (!replaceTitle) {
replaceTitle = linkTitle;
}
replaceString += '"'+replaceTitle+'" ';
}
replaceString += '}}';
$parent.replaceWith(replaceString);
}
});
if (linkLikes.length > 0) {
console.log(file+" --|-- "+linkLikes.length);
console.log('-------------------')
console.log('-------------------')
fs.writeFile(file, $('body').html(), function(err) {
if (err) throw('File save error: '+ err);
console.log('file saved');
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment