首页 > 解决方案 > 在模板文字中键入占位符?

问题描述

所以我正在尝试这个:

    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...

标签: javascripttypescripttemplate-literals

解决方案


模板文字只能创建一个特定的字符串。他们无法表达“任何字符串”的概念。

相反,使用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.


推荐阅读