
本文将介绍一个 JavaScript 函数,该函数用于识别用户在字符串模板中填充的空白,并将其提取出来。该函数能够处理各种情况,包括空白被替换为空字符串以及空白位于单词内部的情况。
解决此问题的关键在于使用正则表达式。我们可以将模板字符串转换为一个正则表达式,其中空白(____)被替换为捕获组 (.*)。这样,我们就可以使用正则表达式的 match 方法从用户的输入中提取出填充的空白内容。
以下是实现此功能的 JavaScript 代码:
const fillBlanks = (template, response, match = response.match(new RegExp(
template.replace(/[/-\^$*+?.()|[]{}]/g, '\$&') // 转义正则表达式特殊字符
.replace(/ /g, '\s*') // 压缩空格
.replace(/____/g, '(.*)'), // 添加捕获组
"m" // 多行匹配
))) => match && match.slice(1);
console.log(fillBlanks('____ World!', 'Hello World!')); //=> ["Hello"]
console.log(fillBlanks('H____o ____World!', 'Hello World!')); //=> ["ell", ""]
const template = `____ = ____("Enter your name")
____(name)`;
const answer = `name = input("Enter your name")
print(name)`;
console.log(fillBlanks(template, answer)); //=> ["name", "input", "print"]代码解释:
立即学习“Java免费学习笔记(深入)”;
fillBlanks(template, response) 函数:
*`template.replace(/[/-^$+?.()|[]{}]/g, '$&')`:**
*`replace(/ /g, 's')`:**
*`replace(/____/g, '(.)')`:**
new RegExp(..., "m"):
match && match.slice(1):
通过使用正则表达式,我们可以有效地从字符串模板中识别用户填充的空白。然而,需要注意空格处理、复杂模板和安全性等问题。在实际应用中,需要根据具体情况选择合适的方法。
以上就是JavaScript 教程:从字符串模板中识别用户填充的空白的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号