I'm getting the following string:
var str='{"message":"hello\nworld"}';
I need to turn it into JSON object. However, I get an exception when I try JSON.parse(str) because of the \n
I saw this question but it did not help.
From that, I tried
var j=JSON.parse(JSON.stringify(str))
But I'm still getting string instead of object when i use typeof j
I know using \\n works, but the thing is, it does not print on new line when i need to use the value.
UPDATE: OK, i just realized \\n is working.
I'm using this to convert \n to \\n:
var str='{"message":"hello\nworld"}';
str=str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t");
var json=JSON.parse(str);
console.log(json.message);
Can someone please correct it?
Escaping \n to \\n was the right thing to do. In your code, the replace call was done wrong. You need fewer slashes. Updated your code :
var str='{"message":"hello\nworld"}';
str=str.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
var json=JSON.parse(str); //No errors due to escaping
Now print it and you'll see the text being split into different lines.
console.log(json.message);
Related
I have to stringify some JS objects to save the text somewhere and I'd like to be able to copy the saved text manually afterwards and pass it via the console to a function which then parses the text to do something with the original object.
Unfortunately parsing pasted text seems to have problems with escaped double quotes since parsing always fails.
I have created a small snippet which illustrates my problem:
http://jsfiddle.net/wgwLcgz6/1/
var jsonStr = JSON.stringify({ arg1: 'some string "with quotes"' });
$('#out1').html(jsonStr); // {"arg1":"some string \"with quotes\""}
JSON.parse(jsonStr); // Works just fine
try {
// Copied the ouput of JSON.stringify manually and pasted it directly into
// the parse function...
JSON.parse('{"arg1":"some string \"with quotes\""}');
// We never get here since an exception is thrown
$('#out2').html('Parsed successfully');
} catch (ex) {
// SyntaxError: Unexpected token w
$('#out2').html(ex.toString());
}
I think I do understand why this is happening even though I can't explain it properly but I don't have any idea on how to circumvent this and would really appreciate some help and maybe deeper explanation.
One more thing: If I paste the stringified object {"arg1":"some string \"with quotes\""} into an online json parser like http://jsonlint.com/ it parses it just fine which I guess is because they use there own parser instead of the browsers built in ones...
You need to escape quotes and backslashes. Since you're using single quotes around a string with double quotes, you just have to escape the backslashes:
JSON.parse('{"arg1":"some string \\"with quotes\\""}');
I have a string with a line-break in the source code of a javascript file, as in:
var str = 'new
line';
Now I want to delete that line-break in the code. I couldn't find anything on this, I kept getting stuff about \n and \r.
Thanks in advance!
EDIT (2021)
This question was asked a long, long time ago, and it's still being viewed relatively often, so let me elaborate on what I was trying to do and why this question is inherently flawed.
What I was trying to accomplish is simply to use syntax like the above (i.e. multi-line strings) and how I could accomplish that, as the above raises a SyntaxError.
However, the code above is just invalid JS. You cannot use code to fix a syntax error, you just can't make syntax errors in valid usable code.
The above can now be accomplished if we use backticks instead of single quotes to turn the string into a template literal:
var str = `new
line`;
is totaly valid and would be identical to
var str = 'new\n line';
As far as removing the newlines goes, I think the answers below address that issue adequately.
If you do not know in advance whether the "new line" is \r or \n (in any combination), easiest is to remove both of them:
str = str.replace(/[\n\r]/g, '');
It does what you ask; you end up with newline. If you want to replace the new line characters with a single space, use
str = str.replace(/[\n\r]+/g, ' ');
str = str.replace(/\n|\r/g,'');
Replaces all instances of \n or \r in a string with an empty string.
I am literally pulling my hair out on this one...
Here's the situation. I have two javascript strings as follows:
dsName = "Test 1"
replacementString = "Test "
I'm trying to see if dsName starts with replacementString, with the following code:
if(dsName.indexOf(replacementString) == 0)
{
// I never get here!
}
indexOf is returning -1!! How is this possible? I can put a breakpoint in Chrome script debugging right before that line and paste "dsName.indexOf(replacementString)" into the console and see that it is indeed returning -1.
Now just to prove I'm not crazy I can from that same breakpoint print out dsName and it does in fact equal "Test 1" and replacementString does equal "Test ". Here is an actual screenshot from the Chrome debugging console:
So as you can see, if I paste in the literal string, it works as expected, but if I use the variable, it doesn't work. I've even tried String(replacementString) and replacementString.toString() to see if maybe it was a type issue, but it does the same thing.
It's like it works if the parameter for indexOf is a literal string, but not if it's a string variable.
Am I going crazy, is there a something stupid I'm missing? Or is this possibly a bug in Chrome?
It looks like some of the characters that look like spaces are not actually simple spaces. Try this to see what the string really contains:
for (var i=0; i<replacementString.length; i++)
console.log(replacementString.charCodeAt(i));
You can replace non-breaking spaces by regular ones like this:
replacementString = replacementString.replace(String.fromCharCode(160), " ");
Kudos to Wolfgang for getting me on the right path to figuring this out, but it turned out to be something completely unexpected and different...
I was pulling the value of replacementText from a <textarea> which had a style of white-space:nowrap. I guess when nowrap is turned on, it returns spaces as non-breaking (ASCII code 160) and not as regular spaces.
Here's a js-fiddle to see what's going on: http://jsfiddle.net/Jk9Cw/
What do you guys think? Is this a "duh you've should have known" or a "wow, that is something I've never run into before"?
In my code, i need to pass the value present in instance variable to javascript, and then use that value to set onto textarea.
$('textarea.myclass').val('<%= #text_value %>');
But if the variable #text_value contains \n (this is\n demo) then, its leads to javascript error and the page shows exactly as this, separated by space in between,
$('textarea.myclass').val('this is
// error message over here
demo');
Any way i can handle this ?
I also faced such situation, and i just escaped the \ to \\, so finally \n to \\n, \r to \\r
$('textarea.myclass').val('<%= #text_value.gsub("\r","\\r").gsub("\n","\\n") %>');
Hope this corrects you error too.
The best answer I can come up with is to go for a variable. Without testing, this may be answer you are looking for:
var newline = "\n";
$('textarea.myclass').val('this is '+newline+' demo');
As SilverBlade suggested, maybe a double backslash would do the trick.
when I get a text from a textarea in html like this
wase&
;#101;m
the correct decode is waseem
notice the newline , when I decode it I get
wase&;#101;m
the newline make errors here , Can I fix it ? I use javascript in the decoding process .
I use this function in decoding
function html_entity_decode(str) {
var ta=document.createElement("textarea");
ta.innerHTML=str.replace(/</g,"<").replace(/>/g,">");
return ta.value;
}
You could pass it through the following regex - Replace
&[\s\r\n]+;(?=#\d+;)
with
&
globally. Your HTML entity format is simply broken. Apart from the fact that HTML entities cannot contain whitespace and newlines, they cannot contain semi-colons in the middle.
Your input text may not be right and it is working as intended. Garbage-In-Garbage-Out.
I suspect the &\n; should be something else. But if not:
str.replace(/&\s*;/g, "");