javascript replace escaped " to work with Json parse - javascript

This is the input of javacript function that arise error after Json.parse
I know double escape string is working with JSON.parse, but how to convert current string to that one... I have tried couple of things, but couln't make it work.
pVis = '[{"Name":"Ecz., - \" Europharma\" \" -\"","Id":"402872"}]';
console.log('before replace'+pVis);
pVis = pVis.replace(/\\/g,"\\\\");
//pVis = '[{"Name":"Ecz., - \\" Europharma\\" \\" -\\"","Id":"402872"}]';
console.log('after replace'+pVis);
pVisitedsJson = JSON.parse(pVis);

Since it's interpreting ' character as escaped, it's impossible for me catch and change it on javascript side. So, I changed from the source.

Related

Why the .replace() and toUppercase() did not work in the second function? [duplicate]

I want to replace the smart quotes like ‘, ’, “ and ” to regular quotes. Also, I wanted to replace the ©, ® and ™. I used the following code. But it doesn't help.
Kindly help me to resolve this issue.
str.replace(/[“”]/g, '"');
str.replace(/[‘’]/g, "'");
Use:
str = str.replace(/[“”]/g, '"');
str = str.replace(/[‘’]/g, "'");
or to do it in one statement:
str = str.replace(/[“”]/g, '"').replace(/[‘’]/g,"'");
In JavaScript (as in many other languages) strings are immutable - string "replacement" methods actually just return the new string instead of modifying the string in place.
The MDN JavaScript reference entry for replace states:
Returns a new string with some or all matches of a pattern replaced by a replacement.
…
This method does not change the String object it is called on. It simply returns a new string.
replace return the resulting string
str = str.replace(/["']/, '');
The OP doesn't say why it isn't working, but there seems to be problems related to the encoding of the file. If I have an ANSI encoded file and I do:
var s = "“This is a test” ‘Another test’";
s = s.replace(/[“”]/g, '"').replace(/[‘’]/g,"'");
document.writeln(s);
I get:
"This is a test" "Another test"
I converted the encoding to UTF-8, fixed the smart quotes (which broke when I changed encoding), then converted back to ANSI and the problem went away.
Note that when I copied and pasted the double and single smart quotes off this page into my test document (ANSI encoded) and ran this code:
var s = "“This is a test” ‘Another test’";
for (var i = 0; i < s.length; i++) {
document.writeln(s.charAt(i) + '=' + s.charCodeAt(i));
}
I discovered that all the smart quotes showed up as ? = 63.
So, to the OP, determine where the smart quotes are originating and make sure they are the character codes you expect them to be. If they are not, consider changing the encoding of the source so they arrive as “ = 8220, ” = 8221, ‘ = 8216 and ’ = 8217. Use my loop to examine the source, if the smart quotes are showing up with any charCodeAt() values other than those I've listed, replace() will not work as written.
To replace all regular quotes with smart quotes, I am using a similar function. You must specify the CharCode as some different computers/browsers default settings may identify the plain characters differently ("",",',').
Using the CharCode with call the ASCII character, which will eliminate the room for error across different browsers, and operating systems. This is also helpful for bilingual use (accents, etc.).
To replace smart quotes with SINGLE QUOTES
function unSmartQuotify(n){
var name = n;
var apos = String.fromCharCode(39);
while (n.indexOf("'") > -1)
name = name.replace("'" , apos);
return name;
}
To find the other ASCII values you may need. Check here.

JSON.parse incorrect string format

i have this string:
"{\\'Ovcount\\':\\'0\\',\\'S1\\':\\'LU\\',\\'S2\\':\\'NewClientOrMove\\',\\'memoToDisplay\\':\\'LU -- New Client or Move\\\"}";
and i want it to become like this:
'{"Ovcount":"0","S1":"LU","S2":"NewClientOrMove","memoToDisplay":"LU -- New Client or Move"}'
I tried with stringify and replace and i ended up with
"{'Ovcount':'0','S1':'LU','S2':'NewClientOrMove','memoToDisplay':'LU -- New Client or Move"}"
And from here i wanted to replace the single quotation marks ' with double quotation marks " but when i did, in beginning and ending of the string appeared an extra "\
"\ "{"Ovcount":"0","S1":"LU","S2":"NewClientOrMove","memoToDisplay":"LU -- New Client or Move\"}\ ""
Any tips on how to get the correct format?
var result = "{\'Ovcount\':\'0\',\'S1\':\'LU\',\'S2\':\'NewClientOrMove\',\'memoToDisplay\':\'LU -- New Client or Move\"}"
.replaceAll("'", '"')
.replaceAll('\\', '');
console.log(result);
this got me what you wanted, it replaces all the single quotes with double quotes, then it removes any back slashes
the result is
'{"Ovcount":"0","S1":"LU","S2":"NewClientOrMove","memoToDisplay":"LU
-- New Client or Move"}'

replace multiple words in string based on an array [duplicate]

I want to replace the smart quotes like ‘, ’, “ and ” to regular quotes. Also, I wanted to replace the ©, ® and ™. I used the following code. But it doesn't help.
Kindly help me to resolve this issue.
str.replace(/[“”]/g, '"');
str.replace(/[‘’]/g, "'");
Use:
str = str.replace(/[“”]/g, '"');
str = str.replace(/[‘’]/g, "'");
or to do it in one statement:
str = str.replace(/[“”]/g, '"').replace(/[‘’]/g,"'");
In JavaScript (as in many other languages) strings are immutable - string "replacement" methods actually just return the new string instead of modifying the string in place.
The MDN JavaScript reference entry for replace states:
Returns a new string with some or all matches of a pattern replaced by a replacement.
…
This method does not change the String object it is called on. It simply returns a new string.
replace return the resulting string
str = str.replace(/["']/, '');
The OP doesn't say why it isn't working, but there seems to be problems related to the encoding of the file. If I have an ANSI encoded file and I do:
var s = "“This is a test” ‘Another test’";
s = s.replace(/[“”]/g, '"').replace(/[‘’]/g,"'");
document.writeln(s);
I get:
"This is a test" "Another test"
I converted the encoding to UTF-8, fixed the smart quotes (which broke when I changed encoding), then converted back to ANSI and the problem went away.
Note that when I copied and pasted the double and single smart quotes off this page into my test document (ANSI encoded) and ran this code:
var s = "“This is a test” ‘Another test’";
for (var i = 0; i < s.length; i++) {
document.writeln(s.charAt(i) + '=' + s.charCodeAt(i));
}
I discovered that all the smart quotes showed up as ? = 63.
So, to the OP, determine where the smart quotes are originating and make sure they are the character codes you expect them to be. If they are not, consider changing the encoding of the source so they arrive as “ = 8220, ” = 8221, ‘ = 8216 and ’ = 8217. Use my loop to examine the source, if the smart quotes are showing up with any charCodeAt() values other than those I've listed, replace() will not work as written.
To replace all regular quotes with smart quotes, I am using a similar function. You must specify the CharCode as some different computers/browsers default settings may identify the plain characters differently ("",",',').
Using the CharCode with call the ASCII character, which will eliminate the room for error across different browsers, and operating systems. This is also helpful for bilingual use (accents, etc.).
To replace smart quotes with SINGLE QUOTES
function unSmartQuotify(n){
var name = n;
var apos = String.fromCharCode(39);
while (n.indexOf("'") > -1)
name = name.replace("'" , apos);
return name;
}
To find the other ASCII values you may need. Check here.

Print string literally in javascript

I was trying to write a function convertStr with JavaScript that will print strings literally when used with console.log(convertStr(str)).
Some examples for input and output
str = '\'"\n\\'
console.log(convertStr(str))
> '\'"\n\\'
For doing this convertStr should convert '\'"\n\\' to '\'\\\'"\\n\\\\\''.
Let us consider a simpler example
str = '\''
convertStr(str) =====> '\'\\\'\''
console.log(convertStr(str)) =====> '\''
The first challenge here is to know whether we are enclosing str with ' or ". I don't think this is possible without making assumption.
Let's assume that str is enclosed using '.
The other challenge is there are lot of cases to handle.
After searching the web I tried few solutions
Attempt 1:
I tried JSON.stringify which breaks when I use escaped string quotes inside str
console.log(JSON.stringify('\"')) =====> "\""
console.log(JSON.stringify('\'')) =====> "'"
This solution fails for case with single quotes. This also fails when we use unicode escape
console.log(JSON.stringify('\u2260') ====> "≠"
Attempt 2:
I tried using str.replace(regex, replacestr) but could not find a solution that works for all cases like unicode or things like \x41 or \0.

Escaping a string to be placed in generated JavaScript source, in JavaScript

I'm writing code that will generate some javascript. The javascript will involve assigning a variable in the generated code to a string passed into the generator. The generator is also in javascript.
Basically I want to do this:
function generate_code(text) {
return "var a = " + jsEscapeString(text) + "; alert(a);";
}
function jsEscapeString(text) {
// WHAT GOES HERE?
// e.g. it needs to:
// - surround with quotes
// - escape quotes inside the text
// - escape backslashes and newlines and other fun characters
// - defend against other horrible things I probably don't know about
}
I don't want something that only works in the happy case. I want something correct. Something that would survive a malicious adversary trying to do sandbox escapes on the resulting code (e.g. like what you do in the game 'Untrusted').
Super easy.
function jsEscapeString(text) {
return JSON.stringify(text);
}
No matter what you put in, you will ALWAYS get a valid representation of it that can be dumped into JS source. The result, when executed, will always be exactly what you put in.
This even works for strings, booleans, numbers, arrays, objects... basically everything you'll ever need.
Although I'm curious as to why you're doing this... This smells of eval fishiness...
You would need to escape backslash, the string delimiter, and control characters:
function jsEscapeString(text) {
return '"' +
text
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
.replace(/\b/g, '\\b')
.replace(/\v/g, '\\v')
.replace(/\f/g, '\\f')
+ '"';
}

Categories

Resources