Skip to content

Instantly share code, notes, and snippets.

@brianpeiris
Last active December 24, 2015 10:19
Show Gist options
  • Save brianpeiris/6783876 to your computer and use it in GitHub Desktop.
Save brianpeiris/6783876 to your computer and use it in GitHub Desktop.
Node script that converts double quotes to single quotes in JavaScript files.
// Taken from http://ariya.ofilabs.com/2012/02/from-double-quotes-to-single-quotes.html
// Usage:
// $ node singlequote.js <input> [output]
(function () {
'use strict';
var fs = require('fs'),
esprima = require('esprima'),
input = process.argv[2],
output = process.argv[3] || input,
offset = 0,
content = fs.readFileSync(input, 'utf-8'),
tokens = esprima.parse(content, { tokens: true, range: true }).tokens;
function convert(literal) {
var result = literal.substring(1, literal.length - 1);
result = result.replace(/'/g, '"');
result = result.replace(/\\"/g, '"');
return '\'' + result + '\'';
}
tokens.forEach(function (token) {
var str;
if (token.type === 'String' && token.value[0] !== '\'') {
str = convert(token.value);
content = content.substring(0, offset + token.range[0]) + str +
content.substring(offset + token.range[1], content.length);
offset += (str.length - token.value.length);
}
});
fs.writeFileSync(output, content);
}());
@vincentjames501
Copy link

Nice! Works great. I would just document that you need esprima installed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment