javascript - 在模板文字中键入占位符?
问题描述
所以我正在尝试这个:
if(location.href == `${base}/tours`) {
console.log("in list")
} else if (location.href == `${base}/tours/${string}`) {
console.log("in detail");
}
我得到这个错误:
'string' only refers to a type, but is being used as a value here.
base
确实是一个变量,string
我希望只是任何字符串的占位符。
我想知道是否甚至可以将类型作为模板文字中的占位符?在第二个中,if
我正在检查baseURL/tours/<any string>
,any string
可能是tour-one
, tour-two
, tour-three
...
解决方案
模板文字只能创建一个特定的字符串。他们无法表达“任何字符串”的概念。
相反,使用startsWith
:
if (location.href.startsWith(`${base}/tours/`)) {
console.log("in detail");
}
或者使用正则表达式:
const pattern = new RegExp(`^${base}/tours/(.*)`);
const result = pattern.exec(location.href);
if (result) {
console.log("in detail");
// The part matched by `(.*)` will also be available as `result[1]`
}
退一步说,最干净的解决方案是使用为您处理这些 URL 的路由器库。例如,在 React 中,您可以使用react-router
.
推荐阅读
- python - 如何在 Python 中为表数据制作正则表达式
- excel - 错误:1004 无法获取工作表函数类的周数属性
- eclipselink - eclipselink JPQL 错误:按项目排序不是有效的表达式
- deployment - 为什么 VS2017 在 Publish 和部署项目的 setup/msi 中不包含 librdkafka
- php - `,` 后的正则表达式捕获由 `AND` 分隔的所有文本
- sql - SSMS 中缺少添加索引箭头
- tensorflow - 在 torchvision.models.resnet34 中训练 resnet 预训练模型时,Pytorch 如何在 ImageNet 中处理图像?
- firebase - 如何在 Spring Boot Project 中的 Heroku 上使用 Google API 凭据
- sql - 试图写一个麻烦的sql join
- zend-framework - Laminas Fieldset 具有静态 InputFilterSpecification