[英]Inserting variables into regular expressions
我正在尝试编写代码,允许用户检查我是否去过特定国家。
我已经尝试通过提示从用户那里获取输入。 获取该输入,将其存储到变量中,然后将该变量插入到正则表达式中。 从那里开始,我尝试在我的国家/地区阵列上使用.some方法,利用正则表达式和用户输入变量来确定我是否去过用户指定的国家/地区。
var countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama', 'Dominican
Republic', 'Brazil', 'Germany', 'France', 'Portugal',
'Spain', 'the Netherlands'];
var userCountry = prompt("Please enter a country", "");
var beenToUserCountry = countries.some(country =>
/^userCountry$/i.test(country));
if (beenToUserCountry) {
document.write(`Yes, I have been to ${userCountry}.`);
} else {
document.write(`No, I haven't been to ${userCountry} yet.`);
}
我希望该代码将为我的国家组成部分的国家/地区打印“是...”,为不属于国家的国家/地区打印“否...”。 相反,我在提示中插入的每个国家都会给我一个“否...”帮助!
您可以为此使用RegExp
对象,这是一个示例:
var countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama', 'Dominican Republic', 'Brazil', 'Germany', 'France', 'Portugal', 'Spain', 'the Netherlands']; var userCountry = prompt("Please enter a country", ""); var beenToUserCountry = countries.some(country => new RegExp(`^${userCountry}$`, "i").test(country)); if (beenToUserCountry) { document.write(`Yes, I have been to ${userCountry}.`); } else { document.write(`No, I haven't been to ${userCountry} yet.`); }
正如@Bergi提到的那样,您可能应该对userCountry
进行转义以从中删除任何特殊字符,您可以在此处找到一个很好的示例来说明如何做
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.