要保持空格转义的新URI,可以使用encodeURIComponent()
函数来对URI进行编码。这个函数能够将URI中的特殊字符进行转义,包括空格。
下面是一个使用encodeURIComponent()
函数的代码示例:
let uri = "https://example.com/my page.html";
let encodedUri = encodeURIComponent(uri);
console.log(encodedUri);
// 输出:https%3A%2F%2Fexample.com%2Fmy%20page.html
在上面的示例中,encodeURIComponent()
函数将空格字符替换为"%20",保持空格的转义。你可以将encodedUri
用作新的URI。
注意,encodeURIComponent()
函数只会对URI中的特殊字符进行转义,而不会对整个URI进行编码。如果你希望对整个URI进行编码,包括协议、域名等部分,可以使用encodeURI()
函数。
let uri = "https://example.com/my page.html";
let encodedUri = encodeURI(uri);
console.log(encodedUri);
// 输出:https://example.com/my%20page.html
在上面的示例中,encodeURI()
函数将空格字符替换为"%20",并将整个URI进行了编码。