Skip to content

Instantly share code, notes, and snippets.

@sigorilla
Forked from fand/no-japanese.js
Last active March 30, 2025 23:45
Show Gist options
  • Save sigorilla/5a9867ff995b76990d4512f70ae7bf43 to your computer and use it in GitHub Desktop.
Save sigorilla/5a9867ff995b76990d4512f70ae7bf43 to your computer and use it in GitHub Desktop.
Eslint rule to forbid writing non-ASCII characters
/**
* @fileoverview Rule to forbid writing non-ASCII characters.
* @author amagitakayosi
*/
"use strict";
/**
* ASCII characters.
*/
var ASCII_REGEXP = new RegExp('([^\x00-\x7F]+)', 'g');
/**
* Allowed types of token for non-ASCII characters.
*/
var ALLOWED_TOKENS = ['RegularExpression', 'String'];
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = function (context) {
var configuration = context.options[0] || {};
return {
Program: function checkForForbiddenCharacters(node) {
var allowedChars = configuration.allowedChars || '';
var allowedCharsRegExp = new RegExp('[' + allowedChars + ']+', 'g');
var errors = [];
var sourceCode = context.getSourceCode();
var tokens = sourceCode.getTokens(node);
tokens.forEach(function (token) {
if (ALLOWED_TOKENS.indexOf(token.type) !== -1) {
return;
}
var value = token.value;
var matches = value.replace(allowedCharsRegExp, '').match(ASCII_REGEXP);
if (matches) {
errors.push({
line: token.loc.start.line,
column: token.loc.start.column + value.indexOf(matches[0]),
char: matches[0]
});
}
});
errors.forEach(function (error) {
context.report(node, {
line: error.line,
column: error.column
}, 'Non-ASCII character "' + error.char + '" found.');
});
}
};
};
module.exports.schema = [{
type: 'object',
properties: {
allowedChars: {
type: 'string'
}
},
additionalProperties: false
}];
@ryoppippi
Copy link

@mitchellh can we allow only emoji?

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