How to escape Backslash in Javascript object literal

自闭症网瘾萝莉.ら 提交于 2020-01-11 11:46:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!