问题
I know question is asked many times, i gone through with all the questions. but none of them is helping my situation. I have a object literal, for one of the property i assign some string which has backslash charecter, but while reading the property the backslash is getting truncated.
I want to use this object literal in JSON.Stringify method. as per JSON, backslash are not allowed. we need to escape it. is there any way ?
i cant modify the data to add an extra backslash, because data is coming from the server. 'localhost\sqlserver'. after that i need to replace it.
Object literal
var data={
s:'localhost\sqlserver'
}
function replaceToUpper(value) {
return value.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
}
//reading the data
alert(replaceToUpper(data.s));
attempt 2 :
var values =JSON.stringify(data); // here that backslash getting trucunated
what do i missing here. check the fiddle Object Literal with Backslash
i cant modify the data to add an extra backslash, because data is coming from the server. 'localhost\sqlserver'. after that i need to replace it. I know adding extra blackslash would help me. but i cant modify the data.
回答1:
use \\ to escape \
var data = { s: 'localhost\\sqlserver'}
JSON.parse(JSON.stringify(data))
回答2:
it is a string literal where \
is an escape character so if you want to use a \
as it is then you need to escape it with another \
like \\
'localhost\\sqlserver'
Demo: Fiddle
来源:https://stackoverflow.com/questions/20207501/how-to-escape-backslash-in-javascript-object-literal