簡體   English   中英

使用JavaScript對#,單引號和雙引號進行編碼

[英]encoding values using javascript for #, single and double quotes

這是我用來通過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腳本)並將此值分配給textarea字段。

例如,這是weburl: http ://hashgurus.com/q.aspx?q=%23BDMELODI_161其中(q =#BDMELODI_161)我正在獲取q(它是查詢字符串)的值並將框架值定為框架。 通過以下代碼,腳本的最終值如下所示:

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

但是我需要在querystring中到底是什么。 預期結果應如下所示:

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM