在javascript中检测模板文字 [英] Detecting template literals in javascript
问题描述
我们有两个潜在值:
const value = `Hello World`;
和
const value = {message: 'Hello World'};
我要做的是有条件的情况,
What I'm trying to do is a conditional where
if(is template literal) {
// Some code
} else {
// Some code
}
我尝试使用
if(String.raw(value)){
} else {
}
但是对象抛出类型错误。有没有人能找到一种简单可靠的方法来检测javascript中的模板文字?
But the object throws a type error. Does anyone have an easy reliable way to detect template literals in javascript?
编辑:这是对提出要求的人的进一步说明。
Here is some further clarification for those who are asking.
const exampleFunc = (value) => {
// If I pass a string or template literal return as is
if (String.raw({raw: value})) return value;
const css = arr(styles).reduce((acc, obj) => {
// Passing an object handles a more complicated set of operations
}
}
在我使用
之前,如果(String.raw(值))返回值;
Before I was using if (String.raw(value)) return value;
这里发生的事情是给我一个类型错误,而不是让我为null。通过将{raw:value}传递给String。原始方法解决了这个问题,现在我可以检测它是字符串/模板文字还是对象。
And what was happening here is it was giving me a type error rather than handing me null. By passing {raw: value} to String.raw instead solved the problem and I can now detect whether its a string/template literal or an object.
对于我为什么要这样做的说明要更长一些故事与React和样式化的组件有关。
The clarifications to why I'm doing it this way is a longer story that has to do with React & styled components.
推荐答案
使用字符串文字和模板文字没有区别(显然,在源代码级别上除外)。
There is no difference between using a string literal and a template literal (except, obviously, on the source code level).
但是您的第一个值
是字符串,而第二个是对象,并且很容易区分:
But your first value
is a string, while the second one is an object, and those are easy to distinguish:
if (typeof value == "string") {
console.log(value)
} else if (typeof value == "object" && typeof value.message == "string") {
console.log(value.message)
}
这篇关于在javascript中检测模板文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!