是否可以通过仅在URL查询字符串中应用编码来转义特殊字符?

有问题的元素是textarea表单字段。我添加到URL的查询字符串在textarea之外的所有地方都可以正常使用。如果我在形式1的textarea字段中输入“ Life is hard”,它将在目标表单中填充textarea字段,因此:“ Life%20is%20hard”是否有任何方法可以在空格后或空格处附加空格而无需编码插件UX之外的任何内容?就像在查询字符串或参数中一样吗?

tgbbhu 回答:是否可以通过仅在URL查询字符串中应用编码来转义特殊字符?

查询字符串的内容总是 URI编码的,这意味着使用它时,您总是必须对其进行URI解码。假设您的查询字符串使用通常的name=value&name=value格式:

const entries = queryString.split("&").map(
    entry => entry.split("=").map(
        part => decodeURIComponent(part)
    )
);

entries现在是包含查询字符串内容的[key,value]数组的数组,已正确解码以供使用(例如填充textarea)。

示例:

const queryString = "this=that&a=b&text1=Life%20is%20good&x=y";

const entries = queryString.split("&").map(
    entry => entry.split("=").map(
        part => decodeURIComponent(part)
    )
);
for (const [name,value] of entries) {
    if (name === "text1") {
        document.getElementById(name).value = value;
    } else {
        console.log(`Value for ${name}: ${value}`);
    }
}
<textarea id="text1"></textarea>

如果查询字符串不是name=value的形式出现,那么,如果它只是文本区域中所需要的,则它会更简单:

theTextArea.value = decodeURIComponent(queryString);

示例:

const queryString = "Life%20is%20good";

document.getElementById("text1").value = decodeURIComponent(queryString);
<textarea id="text1"></textarea>

,

该网址将自行编码,%20表示其工作方式。

快捷方式:

decodeURI(str)

或尝试:

document.write(unescape(str))
本文链接:https://www.f2er.com/3139222.html

大家都在问