我是Nunjucks/Express和Node世界的新手。
我有一个路由文件,它正在从表单字段移植输入的值。我需要检查该值是否包含表达式"gov"。
所以我创建了以下内容:
router.get('/test/output/', function (req, res) {
var emailAdress = req.session.data['accountEmail']
if ('gov' in emailAdress){
isCS = true
}
res.render('test/output.html',{
'email' : emailAdress,
....等等...
这给了我以下错误:
TypeError: Cannot use 'in' operator to search for 'gov' in 'email@email.com'
我知道这与对象和数组有关 - 我只是找不到解决方案 - 我很欣赏它可能很简单。任何帮助都非常感谢。
in
运算符仅适用于对象,不适用于字符串基元。
要在字符串中搜索,可以使用includes
:
emailAdress.includes('gov')
ES5兼容版本(includes
存在之前(:
emailAdress.indexOf('gov') !== -1
或者,也许您可以检查字符串是否以'gov'
结尾:
emailAdress.endsWith('gov')
我的代码最终看起来像这样:
router.get('/test/output/', function (req, res) {
var emailAddress = req.session.data['accountEmail']
var isCS = emailAddress.includes('gov');
res.render('test/output.html',{
'email' : emailAddress,
'cs' : isCS,
'layout' : '2-0',
'h1': 'Create an account',
。等等等等。