简体   繁体   中英

encoding values using javascript for #, single and double quotes

This is the function that I am using to get the value of querystring through javascript.

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, " "));
}

I am also calling this function:

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>

What am I trying to do?
I am getting the value of querystring through the function getParameterByName('q') and then framing a script tag (var script) and assigning this value to a textarea field.

for example this is the weburl: http://hashgurus.com/q.aspx?q=%23BDMELODI_161 where (q = #BDMELODI_161) I am getting the value of q(which is the querystring) and framing the script value. The final value of script looks like this through this code:

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

but i need exactly what is in the querystring. The expected result should be like this:

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

Also I need to take care of single and double quotes of the querystring properly. Is there any function in javascript to encode these values?

If I don't misundersand your aims, using

encodeURIComponent(trendingitemvalue)

should do the work for the hash issue, doesn't it?

I just tested it and it worked, returning the "%23" replacing the "#".

If I misunderstood your question, please tell me where I'm wrong and maybe I can help you!

Kind regards.

To encode it like you would in an URL you should use encodeURIComponent .

After that to insert the value securely in HTML attribute you need to HTML encode it, however there are no methos which simply does this in JS, you should or use a "translator" tag or build your div using the native calls:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM