JavaScript识别模板填空内容的函数问题及优化需求
解决方案:识别字符串模板中的填充内容
问题说明
需要实现一个JavaScript函数,从模板(空白用____标记)和用户填充后的字符串中,提取出空白处的内容。要求支持:
- 空白位于字符串开头/结尾/中间,比如模板
____ world对应输入Hello world,返回["Hello"] - 空白被填充为空字符串,比如模板
H____o ____ world!对应输入Hello world!,返回["ell", ""] - 处理多行代码场景,比如Python习题模板:
____ = ____("Enter your name") ____(name)
对应用户答案:
name = input("Enter your name") print(name)
需提取出["name", "input", "print"]
现存代码的问题
原代码通过空格拆分字符串的方式存在缺陷:
- 无法处理连续空格的情况(比如空填充导致的多空格)
- 匹配逻辑错误,会把包含前后缀的整个单词作为结果,而不是提取空白处的填充内容
- 不支持多行文本的处理
优化后的实现代码
function identifyBlanks(template, filledString) { // 转义模板中的正则特殊字符,避免干扰匹配 const escapedTemplate = template.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // 将模板中的____替换为非贪婪捕获组,用于提取填充内容 const regexPattern = escapedTemplate.replace(/____/g, '(.*?)'); // 创建全局匹配的正则,支持多行 const regex = new RegExp(regexPattern, 'gs'); const matches = []; let match; // 遍历所有匹配结果,收集捕获组内容 while ((match = regex.exec(filledString)) !== null) { // 跳过第一个全匹配项,只取捕获的填充内容 for (let i = 1; i < match.length; i++) { matches.push(match[i]); } } return matches; } // 测试用例1:单词中间的空白+空填充 const template1 = "H____o ____ world!"; const filled1 = "Hello world!"; console.log(identifyBlanks(template1, filled1)); // 输出: ["ell", ""] // 测试用例2:Python代码模板 const template2 = `____ = ____("Enter your name") ____(name)`; const filled2 = `name = input("Enter your name") print(name)`; console.log(identifyBlanks(template2, filled2)); // 输出: ["name", "input", "print"] // 测试用例3:开头空白 const template3 = "____ world"; const filled3 = "Hello world"; console.log(identifyBlanks(template3, filled3)); // 输出: ["Hello"] // 测试用例4:单词内空白 const template4 = "letters a____c"; const filled4 = "letters abc"; console.log(identifyBlanks(template4, filled4)); // 输出: ["b"]
代码说明
- 正则转义:先转义模板中的正则特殊字符(如
()""等),确保模板中的代码符号不会被当作正则语法解析 - 捕获组替换:将模板中的
____替换为(.*?)非贪婪捕获组,确保精准匹配空白位置的填充内容,不会过度匹配 - 全局多行匹配:使用
gs标志实现全局匹配和多行匹配,支持处理多行代码场景 - 结果收集:遍历所有匹配结果,收集每个捕获组的内容,就是对应空白处的填充值
内容的提问来源于stack exchange,提问作者Jacob Barrow
相关产品推荐
相关产品推荐

