Search code examples
javascriptjquerystringhtml-escape-characters

escaping backslash printing two backslashes in javascript


I am just trying to set a variable string that is going to be a classic asp include, and need to contain backslashes in the string URL, but escaping with an extra "\" is not working. This line;

function addWidget(el){
    var widgetAdd = "<!--#include virtual='backoffice\\home\\widgets\\" + el + ".asp-->";
}

returns the string of;

"<!--#include virtual='backoffice\\home\\widgets\\example.asp-->"

I just want the string to contain the proper url with single backslashes not double. If I remove the escaping backslash the string is;

"<!--#include virtual='backofficehomewidgetsexample.asp-->"

thank you


Solution

  • I don't see exactly what you want.. you want the double backslashes or not? if yes do this

    function addWidget(el){
         return "<!--#include virtual='backoffice\\\\home\\\widgets\\\\" + el + ".asp-->";
    }
    

    returns "<!--#include virtual='backoffice\\home\\widgets\\" + el + ".asp-->" you need to escape each backslashe. so one for each = 2 more = \\\\

    if you want to have only one backslash,

    function addWidget(el){
        return "<!--#include virtual='backoffice\\home\\widgets\\" + el + ".asp-->";
    }
    

    should work: it returns "<!--#include virtual='backoffice\home\widgets\" + el + ".asp-->";