使用javascript为#、单引号和双引号编码值



这是我用来通过javascript获取querystring值的函数。

function getParameterByName(name) {
    name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
    var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/+/g, " "));
}

我也调用这个函数:

function GenerateCode() {
    var trendingitemvalue = getParameterByName('q');
    alert(trendingitemvalue);
    var script = "<script async src="//hashgurus.com/feed/Trendingat.js"></script>";
    script += "n<div class="hg-trendingat-widget" hg-trend="" +trendingitemvalue + ""></div>"
    codearea.value = script;
 }
<textarea style="height: 40px; color: blue" id="codearea" onclick="SelectAll(this)"></textarea>

我想做什么
我通过函数getParameterByName('q')获取querystring的值,然后构建一个脚本标记(var脚本),并将该值分配给一个文本区域字段。

例如,这是weburl:http://hashgurus.com/q.aspx?q=%23BDMELODI_161其中(q=#BDMELODI_161)我正在获取q的值(它是查询字符串),并对脚本值进行成帧。通过以下代码,脚本的最终值如下所示:

<div class="hg-trendingat-widget" hg-trend="#BDMELODI_161"></div>

但我需要查询字符串中的确切内容。预期结果应该是这样的:

<div class="hg-trendingat-widget" hg-trend="%23BDMELODI_161"></div>

此外,我还需要正确处理querystring的单引号和双引号。javascript中有任何函数可以对这些值进行编码吗?

如果我没有滥用你的目标,使用

encodeURIComponent(trendingitemvalue)

应该为散列问题做工作,不是吗?

我刚刚测试了它,它起了作用,返回了"%23"代替了"#"。

如果我误解了你的问题,请告诉我哪里错了,也许我可以帮助你!

致以亲切的问候。

要像在URL中那样对其进行编码,应该使用encodeURIComponent

之后,为了在HTML属性中安全地插入值,您需要对其进行HTML编码,然而,在JS中没有简单的方法可以做到这一点,您应该或使用"translator"标记,或使用本地调用构建您的div:

var div = document.createElement('div');
div.setAttribute('hg-trend', encodeURIComponent(trendingitemvalue));
div.className = "hg-trendingat-widget";
//div.outerHTML will return <div...></div>

最新更新