How to parse \n in string while passing the value to javascript - javascript

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.

Related

JSON parse gives error occasionally on parsing string

I have same input fields where the user inputs some data. Next my code converts it to JSON and send it to the server.
$("#submit").click(function(){
var inp = $("#inpTxt").val();
if(inp == null || inp == ""){
return;
}
jsonResult = JSON.parse('{"data": "' + inp + '"}');
$.ajax({
data : jsonResult,
...
});
});
The issue here is that sometimes the above code works and sometimes it just don't.
Most of the time I tested the code it worked like a charm but on productions I keep on getting the error reported several times.
I have not been able to figure out the possible cause yet.
Note: Some parts of the code are not shared in above but only part of what the problem seems to be.
As per the last comment the problem seems to be occurring when someone inputs some escape character in input (#Noob46 identified the case of using "Something" case but in my opinion it will also occur if any other escape character like \ or any other starting with \ may also cause the same problem).
Thus, one way to handle this is to filter the coming input string before passing it to JSON.parse.
To take things a step forward I have created some js that you can find here which in fact will let you handle the escape characters if they come as part of your input.
For further details refer to the attached code and example in the provided link here.
As the problem identified by me so let me also state an answer here. All you need is to add an additional \ before all the escape characters you encounter like:
\b : backspace
\f : form feed
\n : line feed
\r : carriage return
\t : horizontal tab
\v : vertical tab
" : double quote
\ : back slash
You can do so by code like:
inp = inp.replace('"','\\\"');
Or inp.replace('\','\\\\');
And so on for other characters.
When you use JSON.Parse function you need to handle special characters by your self. So if someone puts a " in your inpTxt input it will cause an error on parse that string.
You should do something like the code below to avoid parse error and let javascript correctly handle special characters on your string.
jsonResult = { data: inp };
I create a JS fiddle to make it easier to understand.
https://jsfiddle.net/ub3w0a8x/

Remove new line in javascript code in string

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.

Single Quote in Javascript Param

I have a function that, when clicked, fills in a field of the parent window. In this case, it's a name (text) field.
The problem I'm having is if the field has a single quote in it (ex. Bill's Chili) the function fails because it reads the single quote as the end of the parameter.
Here is the call:
href="javascript:selectItem('recipe','recipe_name','<recipe_description')"
Again, if the name is Bill's Chili, it causes a syntax error.
Is there a way to automatically convert that single quote to the HTML equivalent so it will read properly?
Thanks
For the single quotes in the field use \' More info on escape characters here.
href="javascript:selectItem('Bill\'s Chilli','recipe_name','<recipe_description')"
The answer I found was completely different than I thought. The page itself is written is ASP (Sorry I forgot to mention that, I didn't think it mattered since the function was javascript and it was called in HTML).
Therefore, I just used this:
<%fixed_name = Replace(recipe_name,"'","") %>
And then used fixed_name instead of recipe_name in the function call.
Thanks for all your help, it set me in the right direction!
try this
href='javascript:selectItem("recipe","recipe_name","<recipe_description")'
You may try to use escaped 'double' quote like that:
href="javascript:selectItem(\"recipe\",\"recipe_name\",\"recipe_description\")"
Please let me know whether it works.
You could use str.replace
Just remplace " by " et ' by ' . :)
But actually, I'm assuming you're getting all of that stuff from a php script (from some sort of storage), in which case you could escape the quotes directly with php, that would be way more safer.

Too many quotes within quotes -- what to do?

Here is a section of code used by CKEditor on my website:
CKEDITOR.config.IPS_BBCODE = {"acronym":{"id":"8","title":"Acronym","desc":"Allows you to make an acronym that will display a description when moused over","tag":"acronym","useoption":"1","example":"[acronym='Laugh Out Loud']lol[/acronym]", ...
If you scroll to the right just a little, you will see this:
"[acronym='Laugh Out Loud']lol[/acronym]"
I need to store all of the CKEditor code inside a javascript string, but I can't figure out how to do it because the string has both " and ' in it. See the problem? Furthermore, I don't think I can just escape the quotes because I tried doing that and the editor didn't work.
Any idea what I can do?
You might try taking the string and injecting JavaScript escape codes into it. JavaScript can essentially use any unicode value when using the format: \u#### - so, for a ' character, the code is \u0039, and for the " character, the code is \u0034.
So - you could encode your example portion of the string as:
\u0034[acronym=\u0039Laugh Out Loud\u0039]lol[/acronym]\u0034
Alternatively, you could attempt to simply escape the quotes as in:
\"[acronym=\'Laugh Out Loud\']lol[/acronym]\"
The problem here occurs when you wind up with this kind of situation:
"data:{'prop1':'back\\slash'}"
Which, when escaped in this manner, becomes:
"data:{\'prop\':\'back\\\\slash\'}\"
While this is somewhat more readable than the first version - de-serializing it can be a little tricky when going across object-spaces, such as a javascript object being passed to a C# parser which needs to deserialize into objects, then re-serialize and come back down. Both languages use \ as their escape character, and it is possible to get funky scenarios which are brain-teasers to solve.
The advantage of the \u#### method is that only JavaScript generally uses it in a typical stack - so it is pretty easy to understand what part should be unescaped by what application piece.
hmm.. you said you already tried to escape the quotes and it gave problems.
This shouldn't give problems at all, so try this:
$newstring = addslashes($oldstring);
There's no need to use Unicode escape sequences. Just surround your string with double quotes, and put a backslash before any double quotes within the string.
var x = "\"[acronym='Laugh Out Loud']lol[/acronym]\"";

How to add "\" character in JSON?

I want to add JSON data with the following string value:
json = "d:\xyz\abc";
This value is coming from a database at runtime. When I am going to display it in datatable, JSON formatting error is displayed. My requirement is that the above value will be displayed as it is in the datatable. Please help.
Escape it with another \:
var json = "d:\\xyz\\abc";
You'd better use a JSON library for your programming language. You don't retrieve database values directly with jquery, aren't you?
So, you'd use something like JSON.escape(my_string_from_db), or, in Ruby language I usually do my_string.to_json.
This will automatically escape everything that needs to be escaped.
Change to this:
json = "d:\\xyz\\abc";
See this question for further information
\ is the escape character in JavaScript strings, it gives special meaning to the character following the slash. Like \t is a tab character, \n is a new line. To put a backslash literal you'll need to use \\
The first backslash says the next character is going to be special, the following backslash says "oh, it's just a backslash."

Categories