EJS文件中直接使用substring方法报错,请求排查解决
EJS截取文章内容报错的排查与解决
问题场景
在EJS模板中尝试通过post.content.substring(0, 100) + " ..."截取文章前100字符并添加省略号时触发报错,相关模板代码如下:
<%- include("partials/header"); -%> <h1>Home</h1> <p><%= startingContent %></p> <% posts.forEach(function(post){ %> <h1><%=post.title%></h1> <p> <%=post.content.substring(0, 100) + " ..."%> <!-- This line's giving me an error, I dont know why --> <a href="/posts/<%=post._id%>">Read More</a> </p> <% }) %> <%- include("partials/footer"); -%>
报错原因分析
- post.content 未定义或为空值:如果数据库中部分文章的
content字段缺失、值为null或undefined,直接调用substring方法会触发Cannot read properties of undefined (reading 'substring')类错误。 - post.content 不是字符串类型:若
content存储的是数字、对象等非字符串类型,substring方法仅支持字符串调用,同样会报错。
解决方案
针对上述问题,可通过添加类型判断和空值处理来修复代码,以下是几种可靠实现:
方案1:基础空值与类型校验
通过三元运算符先判断content的存在性与类型,避免非法调用:
<%= post.content && typeof post.content === 'string' ? post.content.substring(0, 100) + " ..." : "暂无内容" %>
方案2:使用可选链简化判断(Node.js 14+支持)
利用ES2020的可选链操作符?.自动处理空值,代码更简洁:
<%= post.content?.substring(0, 100) + " ..." || "暂无内容" %>
方案3:统一转换为字符串
强制将content转为字符串,兼容非字符串类型的场景:
<%= String(post.content || '').substring(0, 100) + " ..." %>
优化建议
如果希望仅在内容长度超过100字符时才添加省略号,可以进一步优化逻辑:
<%= post.content && typeof post.content === 'string' ? (post.content.length > 100 ? post.content.substring(0, 100) + " ..." : post.content) : "暂无内容" %>
内容的提问来源于stack exchange,提问作者justFIDEL
相关产品推荐
相关产品推荐

