1

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.

2
  • i just concentrating the backslash escaping. i don't know why it's not working Commented Nov 26, 2013 at 2:43
  • This question appears to be off-topic because i have changed the data layer such that it escapes the data. as question does not help any other people. pls close it Commented Jan 22, 2014 at 4:28

3 Answers 3

2

use \\ to escape \

var data = { s: 'localhost\\sqlserver'}

JSON.parse(JSON.stringify(data))

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

i cant modify the data, data is coming from the server. 'localhost\sqlserver'. after that i need to replace it. I know this by adding extra backslash. i want to replace it from javascript. not by manually
@Ravi then I don't think you can do much as the string will escape `... try to type 'localhost\sqlserver'` in the browser console the `` is already escaped
1

before save JSON as string into db or somethis use REGEX

JSON.stringify(drivers).replace(/"/g, '\\"')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.