我正在为多行字符串尝试ES6模板文字。以下一个很好用:
var customer = { name: "Foo" }
var card = { amount: 7, product: "Bar", unitprice: 42 }
var message = `Hello ${customer.name},
want to buy ${card.amount} ${card.product} for
a total of ${card.amount * card.unitprice} bucks?`

然后我尝试将其应用于URL字符串,如下所示:
let topic = "pizza";
let url = `https://en.wikipedia.org/w/api.php?action=parse§ion=0&prop=text&format=json&page=${topic}`;

单行版本效果很好。但是,当我将其更改为多行时,它无法正常工作:
let topic = "pizza";
let url = `https://en.wikipedia.org/w/api.php
?action=parse§ion=0&prop=text&format=json&page=${topic}`;
or
let url = `https://en.wikipedia.org/w/api.php\
?action=parse§ion=0&prop=text&format=json&page=${topic}`;

我使用此网址检索数据:
let https = require("https");
https.get(url, res => {...});

有谁能告诉我多线网址有什么问题?我该怎么办?非常感谢。
答案 0 :(得分:1)
您的网址中有换行符。模板文字语法允许您在字符串中添加换行符,如果你在``一边有换行符,那么你的URL中有换行符。
console.log('\n' === `
`) // true
在进行HTTP调用之前,在URL上执行String.prototype.replace()
let topic = "pizza";
let url = `https://en.wikipedia.org/w/api.php
?action=parse§ion=0&prop=text&format=json&page=${topic}`;
\\ removes newline characters from template string
url.replace('\n', '');
\\ do your stuff here
let https = require("https");
https.get(url, res => {...});
或者转义模板字符串中的换行符
let topic = "pizza";
\\ escape the newline character
let url = `https://en.wikipedia.org/w/api.php\
?action=parse§ion=0&prop=text&format=json&page=${topic}`;
\\ do your stuff here
let https = require("https");
https.get(url, res => {...});
答案 1 :(得分:0)
字符串文字保留了您编写行的确切结构。因此,在新行上书写会有效地为您的字符串添加\n
。
let url = `https://en.wikipedia.org/w/api.php\
?action=parse§ion=0&prop=text&format=json&page=${topic}`;
因为字符串实际上是这样的:
let url = `https://en.wikipedia.org/w/api.php\\n?action=parse§ion=0&prop=text&format=json&page=${topic}`;
额外的\n
会向服务器发出错误的请求。
let str = `I
am
a
string
literal`
console.log(str.split('\n'))
编辑:
您可以在每行的末尾添加转义\
以删除\n
。谢谢你的纠正。
let str = `I\
am\
a\
string\
literal`
console.log(str.split('\n'))