简体   繁体   中英

How to escape characters in a string

Consider below response of ajax-

function validateVar(){
    $.ajax({
        url:"abc.do",
        datatype:"text",
        success:function(response){
            alert(response);    //"asdjakd"fsd'f'fsf"s'dfs'df"fsdf"fsfsf""
        }
    });
}

I want to escape all occurrences of quotes in the response.

JSFIDDLE: https://jsfiddle.net/ashwyn/3w0aj5z7/

You can use the backslash to escape a character \\ . So to store your string in a variable we can write it like this.

var v = "asdjakd\"fsd\'f\'fsf\"s\'dfs\'df\"fsdf\"fsfsf";

You can't programmatically escape a string to make it valid JavaScript.

It has to be valid JavaScript to get through the JavaScript parser before it can be modified by JavaScript.

You have to fix it in the source code.

The \\ character starts an escape sequence in a JavaScript string literal:

var v = "asdjakd\"fsd'f'fsf\"s'dfs'df\"fsdf\"fsfsf";

You need to escape the double quotationmark " with backslash \\

Your string should look like this:

"asdjakd\\"fsd'f'fsf\\"s'dfs'df\\"fsdf\\"fsfsf"

You can use backslash to solve this You need to add backslash for same type inverted commas(single or double).

function validateVar(){
   var v = "asdjakd\"fsd'f'fsf\"s'dfs'df\"fsdf\"fsfsf";
   alert(v);
}

Update the fiddle as well, check here :: https://jsfiddle.net/3w0aj5z7/1/

You can include the string between '' or "" . Then you must say to the variable where quotes aren't the closing ones with \\ before it.

In this case:

var v = ' "asdjakd"fsd\'f\'fsf"s\'dfs\'df"fsdf"fsfsf" ';

before ' quote

or

var v = " \"asdjakd\"fsd'f'fsf\"s'dfs'df\"fsdf\"fsfsf\" ";

before " quotes

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