【发布时间】:2021-05-29 19:22:48
【问题描述】:
我正在尝试使用 ejs 模板中的 checkVowel() 函数。但它不起作用。
我从 home.ejs 得到一个字符串输入:
<body>
<div class="header">
<h1>Just enter a string and I will tell you how many vowels are there...</h1>
<form action="/" method="POST">
<label for="strInput">Enter text</label>
<input type="text" id="strInput" name="str">
<input type="submit" value="Submit">
</form>
</div>
</body>
这是我在 functions.ejs 中添加的 JavaScript 部分:
<% function checkVowel(str) {
vowels = ['a', 'e', 'i', 'o', 'u']
vowel_count = 0
for (let i = 0; i < str.length; i++) { if (vowels.includes(str[i])) { vowel_count += 1; } } console.log(`There are ${vowel_count} vowels in the provided string.`)
} %>
我正在使用 req.body 从 Express 解析我的数据。
const express = require('express')
const ejs = require('ejs')
const app = express()
const port = 3000
// View engine setup
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));
// app.use(bodyParser.json());
app.get('/', (req, res) => {
res.render('home')
})
app.post('/', (req, res) => {
const {str} = req.body;
res.render('result', {str})
// res.send(`Okay, checking: ${str}`)
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
我真的很困惑如何运行我的函数。我不知道是将它包含在 .ejs 文件中还是创建一个单独的文件夹并使用 express.static()。
当有人在我的 home.ejs 文件中填写表格时,我想做什么。该字符串在我的 checkVowel() 函数中用作参数,然后在我的 ejs 模板中呈现 vowel_count。
【问题讨论】:
-
const vowel_count = (str.match(/[aeiou]/gi) || []).length;
标签: javascript ejs