How can I use backslashes () in a string?











up vote
23
down vote

favorite
3












I tried many ways to get a single backslash from an executed (I don't mean an input from html).



I can get special characters as tab, new line and many others then escape them to \t or \n or \(someother character) but I cannot get a single backslash when a non-special character is next to it.



I don't want something like:



str = "apple";   // I want this, to return:
console.log(str); // apple


and if I try to get character at 0 then I get a instead of .










share|improve this question
























  • Is your question about strings, or regular expressions? Or regular expressions you're creating via strings (e.g., using new RegExp(string))?
    – T.J. Crowder
    Apr 6 '12 at 10:09












  • I tried every ways, either regular expressions or string methods, but it really seems that there is no way to handle verbatim or raw strings in javascript code.
    – Mik
    Apr 16 '12 at 8:34















up vote
23
down vote

favorite
3












I tried many ways to get a single backslash from an executed (I don't mean an input from html).



I can get special characters as tab, new line and many others then escape them to \t or \n or \(someother character) but I cannot get a single backslash when a non-special character is next to it.



I don't want something like:



str = "apple";   // I want this, to return:
console.log(str); // apple


and if I try to get character at 0 then I get a instead of .










share|improve this question
























  • Is your question about strings, or regular expressions? Or regular expressions you're creating via strings (e.g., using new RegExp(string))?
    – T.J. Crowder
    Apr 6 '12 at 10:09












  • I tried every ways, either regular expressions or string methods, but it really seems that there is no way to handle verbatim or raw strings in javascript code.
    – Mik
    Apr 16 '12 at 8:34













up vote
23
down vote

favorite
3









up vote
23
down vote

favorite
3






3





I tried many ways to get a single backslash from an executed (I don't mean an input from html).



I can get special characters as tab, new line and many others then escape them to \t or \n or \(someother character) but I cannot get a single backslash when a non-special character is next to it.



I don't want something like:



str = "apple";   // I want this, to return:
console.log(str); // apple


and if I try to get character at 0 then I get a instead of .










share|improve this question















I tried many ways to get a single backslash from an executed (I don't mean an input from html).



I can get special characters as tab, new line and many others then escape them to \t or \n or \(someother character) but I cannot get a single backslash when a non-special character is next to it.



I don't want something like:



str = "apple";   // I want this, to return:
console.log(str); // apple


and if I try to get character at 0 then I get a instead of .







javascript string substring backslash






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 1 at 10:54









Liam

15.7k1675125




15.7k1675125










asked Apr 6 '12 at 10:04









Mik

1,54911310




1,54911310












  • Is your question about strings, or regular expressions? Or regular expressions you're creating via strings (e.g., using new RegExp(string))?
    – T.J. Crowder
    Apr 6 '12 at 10:09












  • I tried every ways, either regular expressions or string methods, but it really seems that there is no way to handle verbatim or raw strings in javascript code.
    – Mik
    Apr 16 '12 at 8:34


















  • Is your question about strings, or regular expressions? Or regular expressions you're creating via strings (e.g., using new RegExp(string))?
    – T.J. Crowder
    Apr 6 '12 at 10:09












  • I tried every ways, either regular expressions or string methods, but it really seems that there is no way to handle verbatim or raw strings in javascript code.
    – Mik
    Apr 16 '12 at 8:34
















Is your question about strings, or regular expressions? Or regular expressions you're creating via strings (e.g., using new RegExp(string))?
– T.J. Crowder
Apr 6 '12 at 10:09






Is your question about strings, or regular expressions? Or regular expressions you're creating via strings (e.g., using new RegExp(string))?
– T.J. Crowder
Apr 6 '12 at 10:09














I tried every ways, either regular expressions or string methods, but it really seems that there is no way to handle verbatim or raw strings in javascript code.
– Mik
Apr 16 '12 at 8:34




I tried every ways, either regular expressions or string methods, but it really seems that there is no way to handle verbatim or raw strings in javascript code.
– Mik
Apr 16 '12 at 8:34












4 Answers
4






active

oldest

votes

















up vote
27
down vote













(See ES2015 update at the end of the answer.)



You've tagged your question both string and regex.



In JavaScript, the backslash has special meaning both in string literals and in regular expressions. If you want an actual backslash in the string or regex, you have to write two: \.



This string starts with one backslash, the first one you see in the literal is an escape character telling us to take the next character literally:



var str = "\I have one backslash";


This regular expression will match a single backslash (not two); again, the first one you see in the literal is an escape character telling us to take the next character literally:



var rex = /\/;


If you're using a string to create a regular expression (rather than using a regular expression literal as I did above), note that you're dealing with two levels: The string level, and the regular expression level. So to create a regular expression using a string that matches a single backslash, you end up using four:



// Matches *one* backslash
var rex = new RegExp("\\");


That's because first, you're writing a string literal, but you want to actually put backslashes in it. So you do that with \ for each one backslash you want. But your regex also requires two \ for every one real backslash you want, and so it needs to see two backslashes in the string. Hence, a total of four. This is one of the reasons I avoid using new RegExp(string) whenver I can; I get confused easily. :-)



ES2015 update



Fast-forward to 2015, and as Dolphin_Wood points out the new ES2015 standard gives us template literals, tag functions, and the String.raw function:



// Yes, this unlikely-looking syntax is actually valid ES2015
let str = String.raw`apple`;


str ends up having the characters , a, p, p, l, and e in it. Just be careful there are no ${ in your "string" (template), since this is a template literal and ${ starts a substitution. E.g.:



let foo = "bar";
let str = String.raw`apple${foo}`;


...ends up being applebar. Also note this isn't quite like "verbatim" strings in C# or similar, as sequences matching the LegacyOctalEscapeSequence in the spec are not allowed and cause a syntax error. So for instance



// Fails
let str = String.raw`c:foo12bar`;


...fails because 12 looks like a legacy octal literal.






share|improve this answer























  • How do you console.log() the variable with backslash if it was assigned already (because it came back like that from the server)?
    – kev
    Jan 16 '17 at 3:30










  • @kev: I don't understand the question.
    – T.J. Crowder
    Jan 16 '17 at 6:59










  • $.ajax({}).done(function(data){console.log(data)}) Output: Object {apple: "apple"} but server actually sent: {"apple": "apple"}. Does it need to be escaped on the server or is there a pure client side solution?
    – kev
    Jan 17 '17 at 0:13






  • 1




    @kev: What the server sent is invalid JSON. JSON (unlike JavaScript) doesn't tolerate undefined escape sequences (a). If that's meant to be a backslash, yes, it must be escaped server-side: {"apple":"\apple"}. (You'd want to even if JSON tolerated invalid escapes, because of {"nectarine":"nectarine"}, where that would be <CR>ectarine because n is a newline.)
    – T.J. Crowder
    Jan 17 '17 at 7:36












  • It looks like the 12 kind of restrictions (there were also issues with u, x etc.) went away sometime after late 2016, so in modern browsers the only thing to avoid is ${
    – ShreevatsaR
    Feb 13 at 21:41




















up vote
11
down vote













is an escape character, when followed by a non-special character it doesn't become a literal . Instead, you have to double it \.



console.log("apple");  //-> "apple" 
console.log("\apple"); //-> "apple"


There is no way to get the original, raw string definition or create a literal string without escape characters.






share|improve this answer

















  • 5




    raw string becomes possible via es6 String.raw method
    – Dolphin_Wood
    Jun 10 '15 at 6:42


















up vote
7
down vote













Try String.raw method:



str = String.raw`apple` // "apple"


Reference here: String.raw()






share|improve this answer

















  • 2




    Just be careful you don't have ${ anywhere in the template literal. :-)
    – T.J. Crowder
    Jan 9 '16 at 11:28








  • 1




    And you can't have octal literals in template strings either such as 12 so this isn't really an effective general technique for avoiding backslash escaping.
    – Wyck
    Aug 25 '16 at 14:56


















up vote
0
down vote













str = "apple" escapes the first a, so you're left with a as the first character. There's no way (afaik) to make "apple" keep that '' without escaping it. You could automate the escaping like this though:



String.prototype.esc = function(){
return '\'+this;
}
//and use it as
var str = 'a'.esc()+'pple';
//or
var str = 'apple'.esc();
//tests
str[0]; //=> ''
str.match(/\/); //=> ['']
RegExp('\\').test(str); //=> true
str.substr(0,1); // ''





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10041998%2fhow-can-i-use-backslashes-in-a-string%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    27
    down vote













    (See ES2015 update at the end of the answer.)



    You've tagged your question both string and regex.



    In JavaScript, the backslash has special meaning both in string literals and in regular expressions. If you want an actual backslash in the string or regex, you have to write two: \.



    This string starts with one backslash, the first one you see in the literal is an escape character telling us to take the next character literally:



    var str = "\I have one backslash";


    This regular expression will match a single backslash (not two); again, the first one you see in the literal is an escape character telling us to take the next character literally:



    var rex = /\/;


    If you're using a string to create a regular expression (rather than using a regular expression literal as I did above), note that you're dealing with two levels: The string level, and the regular expression level. So to create a regular expression using a string that matches a single backslash, you end up using four:



    // Matches *one* backslash
    var rex = new RegExp("\\");


    That's because first, you're writing a string literal, but you want to actually put backslashes in it. So you do that with \ for each one backslash you want. But your regex also requires two \ for every one real backslash you want, and so it needs to see two backslashes in the string. Hence, a total of four. This is one of the reasons I avoid using new RegExp(string) whenver I can; I get confused easily. :-)



    ES2015 update



    Fast-forward to 2015, and as Dolphin_Wood points out the new ES2015 standard gives us template literals, tag functions, and the String.raw function:



    // Yes, this unlikely-looking syntax is actually valid ES2015
    let str = String.raw`apple`;


    str ends up having the characters , a, p, p, l, and e in it. Just be careful there are no ${ in your "string" (template), since this is a template literal and ${ starts a substitution. E.g.:



    let foo = "bar";
    let str = String.raw`apple${foo}`;


    ...ends up being applebar. Also note this isn't quite like "verbatim" strings in C# or similar, as sequences matching the LegacyOctalEscapeSequence in the spec are not allowed and cause a syntax error. So for instance



    // Fails
    let str = String.raw`c:foo12bar`;


    ...fails because 12 looks like a legacy octal literal.






    share|improve this answer























    • How do you console.log() the variable with backslash if it was assigned already (because it came back like that from the server)?
      – kev
      Jan 16 '17 at 3:30










    • @kev: I don't understand the question.
      – T.J. Crowder
      Jan 16 '17 at 6:59










    • $.ajax({}).done(function(data){console.log(data)}) Output: Object {apple: "apple"} but server actually sent: {"apple": "apple"}. Does it need to be escaped on the server or is there a pure client side solution?
      – kev
      Jan 17 '17 at 0:13






    • 1




      @kev: What the server sent is invalid JSON. JSON (unlike JavaScript) doesn't tolerate undefined escape sequences (a). If that's meant to be a backslash, yes, it must be escaped server-side: {"apple":"\apple"}. (You'd want to even if JSON tolerated invalid escapes, because of {"nectarine":"nectarine"}, where that would be <CR>ectarine because n is a newline.)
      – T.J. Crowder
      Jan 17 '17 at 7:36












    • It looks like the 12 kind of restrictions (there were also issues with u, x etc.) went away sometime after late 2016, so in modern browsers the only thing to avoid is ${
      – ShreevatsaR
      Feb 13 at 21:41

















    up vote
    27
    down vote













    (See ES2015 update at the end of the answer.)



    You've tagged your question both string and regex.



    In JavaScript, the backslash has special meaning both in string literals and in regular expressions. If you want an actual backslash in the string or regex, you have to write two: \.



    This string starts with one backslash, the first one you see in the literal is an escape character telling us to take the next character literally:



    var str = "\I have one backslash";


    This regular expression will match a single backslash (not two); again, the first one you see in the literal is an escape character telling us to take the next character literally:



    var rex = /\/;


    If you're using a string to create a regular expression (rather than using a regular expression literal as I did above), note that you're dealing with two levels: The string level, and the regular expression level. So to create a regular expression using a string that matches a single backslash, you end up using four:



    // Matches *one* backslash
    var rex = new RegExp("\\");


    That's because first, you're writing a string literal, but you want to actually put backslashes in it. So you do that with \ for each one backslash you want. But your regex also requires two \ for every one real backslash you want, and so it needs to see two backslashes in the string. Hence, a total of four. This is one of the reasons I avoid using new RegExp(string) whenver I can; I get confused easily. :-)



    ES2015 update



    Fast-forward to 2015, and as Dolphin_Wood points out the new ES2015 standard gives us template literals, tag functions, and the String.raw function:



    // Yes, this unlikely-looking syntax is actually valid ES2015
    let str = String.raw`apple`;


    str ends up having the characters , a, p, p, l, and e in it. Just be careful there are no ${ in your "string" (template), since this is a template literal and ${ starts a substitution. E.g.:



    let foo = "bar";
    let str = String.raw`apple${foo}`;


    ...ends up being applebar. Also note this isn't quite like "verbatim" strings in C# or similar, as sequences matching the LegacyOctalEscapeSequence in the spec are not allowed and cause a syntax error. So for instance



    // Fails
    let str = String.raw`c:foo12bar`;


    ...fails because 12 looks like a legacy octal literal.






    share|improve this answer























    • How do you console.log() the variable with backslash if it was assigned already (because it came back like that from the server)?
      – kev
      Jan 16 '17 at 3:30










    • @kev: I don't understand the question.
      – T.J. Crowder
      Jan 16 '17 at 6:59










    • $.ajax({}).done(function(data){console.log(data)}) Output: Object {apple: "apple"} but server actually sent: {"apple": "apple"}. Does it need to be escaped on the server or is there a pure client side solution?
      – kev
      Jan 17 '17 at 0:13






    • 1




      @kev: What the server sent is invalid JSON. JSON (unlike JavaScript) doesn't tolerate undefined escape sequences (a). If that's meant to be a backslash, yes, it must be escaped server-side: {"apple":"\apple"}. (You'd want to even if JSON tolerated invalid escapes, because of {"nectarine":"nectarine"}, where that would be <CR>ectarine because n is a newline.)
      – T.J. Crowder
      Jan 17 '17 at 7:36












    • It looks like the 12 kind of restrictions (there were also issues with u, x etc.) went away sometime after late 2016, so in modern browsers the only thing to avoid is ${
      – ShreevatsaR
      Feb 13 at 21:41















    up vote
    27
    down vote










    up vote
    27
    down vote









    (See ES2015 update at the end of the answer.)



    You've tagged your question both string and regex.



    In JavaScript, the backslash has special meaning both in string literals and in regular expressions. If you want an actual backslash in the string or regex, you have to write two: \.



    This string starts with one backslash, the first one you see in the literal is an escape character telling us to take the next character literally:



    var str = "\I have one backslash";


    This regular expression will match a single backslash (not two); again, the first one you see in the literal is an escape character telling us to take the next character literally:



    var rex = /\/;


    If you're using a string to create a regular expression (rather than using a regular expression literal as I did above), note that you're dealing with two levels: The string level, and the regular expression level. So to create a regular expression using a string that matches a single backslash, you end up using four:



    // Matches *one* backslash
    var rex = new RegExp("\\");


    That's because first, you're writing a string literal, but you want to actually put backslashes in it. So you do that with \ for each one backslash you want. But your regex also requires two \ for every one real backslash you want, and so it needs to see two backslashes in the string. Hence, a total of four. This is one of the reasons I avoid using new RegExp(string) whenver I can; I get confused easily. :-)



    ES2015 update



    Fast-forward to 2015, and as Dolphin_Wood points out the new ES2015 standard gives us template literals, tag functions, and the String.raw function:



    // Yes, this unlikely-looking syntax is actually valid ES2015
    let str = String.raw`apple`;


    str ends up having the characters , a, p, p, l, and e in it. Just be careful there are no ${ in your "string" (template), since this is a template literal and ${ starts a substitution. E.g.:



    let foo = "bar";
    let str = String.raw`apple${foo}`;


    ...ends up being applebar. Also note this isn't quite like "verbatim" strings in C# or similar, as sequences matching the LegacyOctalEscapeSequence in the spec are not allowed and cause a syntax error. So for instance



    // Fails
    let str = String.raw`c:foo12bar`;


    ...fails because 12 looks like a legacy octal literal.






    share|improve this answer














    (See ES2015 update at the end of the answer.)



    You've tagged your question both string and regex.



    In JavaScript, the backslash has special meaning both in string literals and in regular expressions. If you want an actual backslash in the string or regex, you have to write two: \.



    This string starts with one backslash, the first one you see in the literal is an escape character telling us to take the next character literally:



    var str = "\I have one backslash";


    This regular expression will match a single backslash (not two); again, the first one you see in the literal is an escape character telling us to take the next character literally:



    var rex = /\/;


    If you're using a string to create a regular expression (rather than using a regular expression literal as I did above), note that you're dealing with two levels: The string level, and the regular expression level. So to create a regular expression using a string that matches a single backslash, you end up using four:



    // Matches *one* backslash
    var rex = new RegExp("\\");


    That's because first, you're writing a string literal, but you want to actually put backslashes in it. So you do that with \ for each one backslash you want. But your regex also requires two \ for every one real backslash you want, and so it needs to see two backslashes in the string. Hence, a total of four. This is one of the reasons I avoid using new RegExp(string) whenver I can; I get confused easily. :-)



    ES2015 update



    Fast-forward to 2015, and as Dolphin_Wood points out the new ES2015 standard gives us template literals, tag functions, and the String.raw function:



    // Yes, this unlikely-looking syntax is actually valid ES2015
    let str = String.raw`apple`;


    str ends up having the characters , a, p, p, l, and e in it. Just be careful there are no ${ in your "string" (template), since this is a template literal and ${ starts a substitution. E.g.:



    let foo = "bar";
    let str = String.raw`apple${foo}`;


    ...ends up being applebar. Also note this isn't quite like "verbatim" strings in C# or similar, as sequences matching the LegacyOctalEscapeSequence in the spec are not allowed and cause a syntax error. So for instance



    // Fails
    let str = String.raw`c:foo12bar`;


    ...fails because 12 looks like a legacy octal literal.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited May 23 '17 at 11:53









    Community

    11




    11










    answered Apr 6 '12 at 10:12









    T.J. Crowder

    666k11611741269




    666k11611741269












    • How do you console.log() the variable with backslash if it was assigned already (because it came back like that from the server)?
      – kev
      Jan 16 '17 at 3:30










    • @kev: I don't understand the question.
      – T.J. Crowder
      Jan 16 '17 at 6:59










    • $.ajax({}).done(function(data){console.log(data)}) Output: Object {apple: "apple"} but server actually sent: {"apple": "apple"}. Does it need to be escaped on the server or is there a pure client side solution?
      – kev
      Jan 17 '17 at 0:13






    • 1




      @kev: What the server sent is invalid JSON. JSON (unlike JavaScript) doesn't tolerate undefined escape sequences (a). If that's meant to be a backslash, yes, it must be escaped server-side: {"apple":"\apple"}. (You'd want to even if JSON tolerated invalid escapes, because of {"nectarine":"nectarine"}, where that would be <CR>ectarine because n is a newline.)
      – T.J. Crowder
      Jan 17 '17 at 7:36












    • It looks like the 12 kind of restrictions (there were also issues with u, x etc.) went away sometime after late 2016, so in modern browsers the only thing to avoid is ${
      – ShreevatsaR
      Feb 13 at 21:41




















    • How do you console.log() the variable with backslash if it was assigned already (because it came back like that from the server)?
      – kev
      Jan 16 '17 at 3:30










    • @kev: I don't understand the question.
      – T.J. Crowder
      Jan 16 '17 at 6:59










    • $.ajax({}).done(function(data){console.log(data)}) Output: Object {apple: "apple"} but server actually sent: {"apple": "apple"}. Does it need to be escaped on the server or is there a pure client side solution?
      – kev
      Jan 17 '17 at 0:13






    • 1




      @kev: What the server sent is invalid JSON. JSON (unlike JavaScript) doesn't tolerate undefined escape sequences (a). If that's meant to be a backslash, yes, it must be escaped server-side: {"apple":"\apple"}. (You'd want to even if JSON tolerated invalid escapes, because of {"nectarine":"nectarine"}, where that would be <CR>ectarine because n is a newline.)
      – T.J. Crowder
      Jan 17 '17 at 7:36












    • It looks like the 12 kind of restrictions (there were also issues with u, x etc.) went away sometime after late 2016, so in modern browsers the only thing to avoid is ${
      – ShreevatsaR
      Feb 13 at 21:41


















    How do you console.log() the variable with backslash if it was assigned already (because it came back like that from the server)?
    – kev
    Jan 16 '17 at 3:30




    How do you console.log() the variable with backslash if it was assigned already (because it came back like that from the server)?
    – kev
    Jan 16 '17 at 3:30












    @kev: I don't understand the question.
    – T.J. Crowder
    Jan 16 '17 at 6:59




    @kev: I don't understand the question.
    – T.J. Crowder
    Jan 16 '17 at 6:59












    $.ajax({}).done(function(data){console.log(data)}) Output: Object {apple: "apple"} but server actually sent: {"apple": "apple"}. Does it need to be escaped on the server or is there a pure client side solution?
    – kev
    Jan 17 '17 at 0:13




    $.ajax({}).done(function(data){console.log(data)}) Output: Object {apple: "apple"} but server actually sent: {"apple": "apple"}. Does it need to be escaped on the server or is there a pure client side solution?
    – kev
    Jan 17 '17 at 0:13




    1




    1




    @kev: What the server sent is invalid JSON. JSON (unlike JavaScript) doesn't tolerate undefined escape sequences (a). If that's meant to be a backslash, yes, it must be escaped server-side: {"apple":"\apple"}. (You'd want to even if JSON tolerated invalid escapes, because of {"nectarine":"nectarine"}, where that would be <CR>ectarine because n is a newline.)
    – T.J. Crowder
    Jan 17 '17 at 7:36






    @kev: What the server sent is invalid JSON. JSON (unlike JavaScript) doesn't tolerate undefined escape sequences (a). If that's meant to be a backslash, yes, it must be escaped server-side: {"apple":"\apple"}. (You'd want to even if JSON tolerated invalid escapes, because of {"nectarine":"nectarine"}, where that would be <CR>ectarine because n is a newline.)
    – T.J. Crowder
    Jan 17 '17 at 7:36














    It looks like the 12 kind of restrictions (there were also issues with u, x etc.) went away sometime after late 2016, so in modern browsers the only thing to avoid is ${
    – ShreevatsaR
    Feb 13 at 21:41






    It looks like the 12 kind of restrictions (there were also issues with u, x etc.) went away sometime after late 2016, so in modern browsers the only thing to avoid is ${
    – ShreevatsaR
    Feb 13 at 21:41














    up vote
    11
    down vote













    is an escape character, when followed by a non-special character it doesn't become a literal . Instead, you have to double it \.



    console.log("apple");  //-> "apple" 
    console.log("\apple"); //-> "apple"


    There is no way to get the original, raw string definition or create a literal string without escape characters.






    share|improve this answer

















    • 5




      raw string becomes possible via es6 String.raw method
      – Dolphin_Wood
      Jun 10 '15 at 6:42















    up vote
    11
    down vote













    is an escape character, when followed by a non-special character it doesn't become a literal . Instead, you have to double it \.



    console.log("apple");  //-> "apple" 
    console.log("\apple"); //-> "apple"


    There is no way to get the original, raw string definition or create a literal string without escape characters.






    share|improve this answer

















    • 5




      raw string becomes possible via es6 String.raw method
      – Dolphin_Wood
      Jun 10 '15 at 6:42













    up vote
    11
    down vote










    up vote
    11
    down vote









    is an escape character, when followed by a non-special character it doesn't become a literal . Instead, you have to double it \.



    console.log("apple");  //-> "apple" 
    console.log("\apple"); //-> "apple"


    There is no way to get the original, raw string definition or create a literal string without escape characters.






    share|improve this answer












    is an escape character, when followed by a non-special character it doesn't become a literal . Instead, you have to double it \.



    console.log("apple");  //-> "apple" 
    console.log("\apple"); //-> "apple"


    There is no way to get the original, raw string definition or create a literal string without escape characters.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Apr 6 '12 at 10:07









    Andy E

    258k64415417




    258k64415417








    • 5




      raw string becomes possible via es6 String.raw method
      – Dolphin_Wood
      Jun 10 '15 at 6:42














    • 5




      raw string becomes possible via es6 String.raw method
      – Dolphin_Wood
      Jun 10 '15 at 6:42








    5




    5




    raw string becomes possible via es6 String.raw method
    – Dolphin_Wood
    Jun 10 '15 at 6:42




    raw string becomes possible via es6 String.raw method
    – Dolphin_Wood
    Jun 10 '15 at 6:42










    up vote
    7
    down vote













    Try String.raw method:



    str = String.raw`apple` // "apple"


    Reference here: String.raw()






    share|improve this answer

















    • 2




      Just be careful you don't have ${ anywhere in the template literal. :-)
      – T.J. Crowder
      Jan 9 '16 at 11:28








    • 1




      And you can't have octal literals in template strings either such as 12 so this isn't really an effective general technique for avoiding backslash escaping.
      – Wyck
      Aug 25 '16 at 14:56















    up vote
    7
    down vote













    Try String.raw method:



    str = String.raw`apple` // "apple"


    Reference here: String.raw()






    share|improve this answer

















    • 2




      Just be careful you don't have ${ anywhere in the template literal. :-)
      – T.J. Crowder
      Jan 9 '16 at 11:28








    • 1




      And you can't have octal literals in template strings either such as 12 so this isn't really an effective general technique for avoiding backslash escaping.
      – Wyck
      Aug 25 '16 at 14:56













    up vote
    7
    down vote










    up vote
    7
    down vote









    Try String.raw method:



    str = String.raw`apple` // "apple"


    Reference here: String.raw()






    share|improve this answer












    Try String.raw method:



    str = String.raw`apple` // "apple"


    Reference here: String.raw()







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jun 10 '15 at 6:33









    Dolphin_Wood

    519314




    519314








    • 2




      Just be careful you don't have ${ anywhere in the template literal. :-)
      – T.J. Crowder
      Jan 9 '16 at 11:28








    • 1




      And you can't have octal literals in template strings either such as 12 so this isn't really an effective general technique for avoiding backslash escaping.
      – Wyck
      Aug 25 '16 at 14:56














    • 2




      Just be careful you don't have ${ anywhere in the template literal. :-)
      – T.J. Crowder
      Jan 9 '16 at 11:28








    • 1




      And you can't have octal literals in template strings either such as 12 so this isn't really an effective general technique for avoiding backslash escaping.
      – Wyck
      Aug 25 '16 at 14:56








    2




    2




    Just be careful you don't have ${ anywhere in the template literal. :-)
    – T.J. Crowder
    Jan 9 '16 at 11:28






    Just be careful you don't have ${ anywhere in the template literal. :-)
    – T.J. Crowder
    Jan 9 '16 at 11:28






    1




    1




    And you can't have octal literals in template strings either such as 12 so this isn't really an effective general technique for avoiding backslash escaping.
    – Wyck
    Aug 25 '16 at 14:56




    And you can't have octal literals in template strings either such as 12 so this isn't really an effective general technique for avoiding backslash escaping.
    – Wyck
    Aug 25 '16 at 14:56










    up vote
    0
    down vote













    str = "apple" escapes the first a, so you're left with a as the first character. There's no way (afaik) to make "apple" keep that '' without escaping it. You could automate the escaping like this though:



    String.prototype.esc = function(){
    return '\'+this;
    }
    //and use it as
    var str = 'a'.esc()+'pple';
    //or
    var str = 'apple'.esc();
    //tests
    str[0]; //=> ''
    str.match(/\/); //=> ['']
    RegExp('\\').test(str); //=> true
    str.substr(0,1); // ''





    share|improve this answer



























      up vote
      0
      down vote













      str = "apple" escapes the first a, so you're left with a as the first character. There's no way (afaik) to make "apple" keep that '' without escaping it. You could automate the escaping like this though:



      String.prototype.esc = function(){
      return '\'+this;
      }
      //and use it as
      var str = 'a'.esc()+'pple';
      //or
      var str = 'apple'.esc();
      //tests
      str[0]; //=> ''
      str.match(/\/); //=> ['']
      RegExp('\\').test(str); //=> true
      str.substr(0,1); // ''





      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        str = "apple" escapes the first a, so you're left with a as the first character. There's no way (afaik) to make "apple" keep that '' without escaping it. You could automate the escaping like this though:



        String.prototype.esc = function(){
        return '\'+this;
        }
        //and use it as
        var str = 'a'.esc()+'pple';
        //or
        var str = 'apple'.esc();
        //tests
        str[0]; //=> ''
        str.match(/\/); //=> ['']
        RegExp('\\').test(str); //=> true
        str.substr(0,1); // ''





        share|improve this answer














        str = "apple" escapes the first a, so you're left with a as the first character. There's no way (afaik) to make "apple" keep that '' without escaping it. You could automate the escaping like this though:



        String.prototype.esc = function(){
        return '\'+this;
        }
        //and use it as
        var str = 'a'.esc()+'pple';
        //or
        var str = 'apple'.esc();
        //tests
        str[0]; //=> ''
        str.match(/\/); //=> ['']
        RegExp('\\').test(str); //=> true
        str.substr(0,1); // ''






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 6 '12 at 10:22

























        answered Apr 6 '12 at 10:11









        KooiInc

        78.9k20108141




        78.9k20108141






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10041998%2fhow-can-i-use-backslashes-in-a-string%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            Popular posts from this blog

            Schultheiß

            Liste der Kulturdenkmale in Wilsdruff

            Android Play Services Check