[英]Preparing strings to be passed into API query (escaping special characters)
I've run into some difficulties with strings and the Fetch API.我在使用字符串和获取 API 时遇到了一些困难。 I've got a React component that accepts a string, sets it to a variable and then constructs a query variable I can pass into
fetch()
.我有一个 React 组件,它接受一个字符串,将它设置为一个变量,然后构造一个可以传递给
fetch()
的查询变量。
The problem is accounting for special characters causing a 404 response.问题在于导致 404 响应的特殊字符。 Here are some examples of strings I'm working with, and their desired output.
以下是我正在使用的一些字符串示例,以及它们所需的 output。
INPUT >>> DESIRED OUTPUT
Something's going on here >>> somethings-going-on-here
Dungeons & dragons >>> dungeons-%26-dragons
It's happening, right here >>> its-happening-right-here
I have the following regex, but it's not quite there yet (it's missing converting the &
to %26
)我有以下正则表达式,但还没有(它缺少将
&
转换为%26
)
replace(/,?\s+/g, '-')
I had looked at using encodeURIComponent
function but it doesn't seem to account for single quotes, which is how I landed up on regex.我看过使用
encodeURIComponent
function 但它似乎没有考虑单引号,这就是我使用正则表达式的方式。
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
var params = new URLSearchParams();
params.set('param1',`Something's going on here`);
params.toString();
You can also use a library that takes care of it for you: https://www.npmjs.com/package/query-string https://www.npmjs.com/package/qs您还可以使用为您处理它的库: https://www.npmjs.com/package/query-string https://www.npmjs.com/package/qs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.