选项 1:标准化
替换所有不明确的标记,并删除空格和分号
const input = `this.variable='test'`
const expected = `this.variable = "test";`
const normalize = (str) => str.trim().toLowerCase().replace(/(\s|;)/g, '').replace(/\"/g, '\'')
console.log(normalize(input));
console.log(normalize(expected));
console.log(normalize(input) === normalize(expected))
选项 2:语义分析
您可以使用esprima 之类的工具来分析用户输入,然后将其与您的预期进行比较:
var esprima = require('esprima');
const input = `this.variable='test'`
console.log(esprima.tokenize(input));
// [
// { type: 'Keyword', value: 'this' },
// { type: 'Punctuator', value: '.' },
// { type: 'Identifier', value: 'variable' },
// { type: 'Punctuator', value: '=' },
// { type: 'String', value: "'test'" }
// ]
console.log(esprima.parse(input));
// {
// "type": "Program",
// "body": [
// {
// "type": "ExpressionStatement",
// "expression": {
// "type": "AssignmentExpression",
// "operator": "=",
// "left": {
// "type": "MemberExpression",
// "computed": false,
// "object": {
// "type": "ThisExpression"
// },
// "property": {
// "type": "Identifier",
// "name": "variable"
// }
// },
// "right": {
// "type": "Literal",
// "value": "test",
// "raw": "'test'"
// }
// }
// }
// ],
// "sourceType": "script"
// }