问题描述
我知道问题多次,我经历了所有的问题。但没有一个帮助我的情况。我有一个对象字面值,对于其中一个属性我分配一些具有反斜杠charecter的字符串,但是在读取属性时,反斜杠被截断。我想在JSON.Stringify方法中使用此对象文字。按照JSON,反斜杠是不允许的。我们需要逃脱它。有什么办法吗
我无法修改数据以添加额外的反斜杠,因为数据来自服务器。 localhost\sqlserver。之后我需要更换它。
对象文字
var data = {
s: 'localhost \sqlserver'
}
function replaceToUpper(value){
return value.replace(/ \\\\
/g,\ \\\
)
.replace(/ \\'/ g,\\)
.replace(/ \\& / g,\\\ \\&)
.replace(/ \\r/g,\\r)
.replace(/ \\\t/g,\\ t)
.replace(/ \\b / g,\\b)
.replace(/ \\f / g,\\f );
}
//读取数据
alert(replaceToUpper(data.s));
尝试2:
var values = JSON.stringify(data); //在这里,反斜杠得到trucunated
我在这里丢失了什么检查小提琴
我无法修改数据以添加额外的反斜杠,因为数据来自服务器。 localhost\sqlserver。之后我需要更换它。我知道添加额外的黑名单会帮助我。但是我无法修改数据。
使用\\来转义\
var data = {
s:'localhost\\\sqlserver'}
JSON.parse(JSON.stringify (数据))
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.
use \\ to escape \
var data = { s: 'localhost\\sqlserver'}
JSON.parse(JSON.stringify(data))
这篇关于如何在JavaScript对象文字中转义反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!