【问题标题】:Recommendations for custom string comparison [closed]自定义字符串比较的建议 [关闭]
【发布时间】:2026-01-26 01:05:02
【问题描述】:

我正在构建一个代码课程平台。用户的屏幕右侧有一个文档,左侧有一个交互式 IDE 供练习。代码验证是通过检查用户的答案(他的整个代码压缩在一个字符串中)是否包含所有要求(几个“强制”字符串)来完成的。

平台运行良好,除了一点,这种逻辑不灵活。例如:

如果预期的答案是this.variable = "test";,则不会接受this.variable='test'

这只是双/单引号、空格和分号的问题。

所以我想知道最好的选择是什么。创建一个自定义的indexOf() 函数,该函数将排除空格和分号并将单引号和双引号视为同一件事?或者也许是一个专门的图书馆?

【问题讨论】:

    标签: javascript string comparator


    【解决方案1】:

    选项 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"
    // }
    

    【讨论】:

    • 非常感谢,这正是我所需要的