Escaping apostrophe (single quote) character in javascript and html - javascript

I have a following situation:
I compose a string in javascript that include apostrophe character. That string is actually html code that is later attached to html using innerHTML method. So the code looks something like this:
var str = 'link'; (argument of the foo function is string)
And after that, this string is inserted into some html element like this:
dataHolder.innerHTML = str;
I've tried to escape ' character with ', ' and \u0027 but all of that is rendered as ' after innerHTML method is called, so when the method foo from the example above is called by clicking on link I always get javascript error saying: Uncaught SyntaxError: missing ) after argument list

You need to have both ' and " in your string, so you will need a third way to delcare a string, you can use template strings for that. Declare your ba'r string as a template string and escape its apostrophe using a backslash \:
document.querySelector('#myDiv').innerHTML =
'link';
function foo(data) {
console.log(data);
}
<div id="myDiv"></div>

use \' instead of ' inside the string, so it should be
var str = 'link';
However, this code is just correct in string format aspect. I think what you want could be
var str = 'link';

You can also use the backtick ` to avoid this problem:
var str = `link`;

Related

Pass this and string as parameter in jquery function

I try to append this following tag which has an onclick function.
$("body").append('<img onclick="removeDynamicColumn(this,'someString')" src="css/images/builder/removeTDTR.png"/>');
In this function I am passing two parameters one is, the element itself and another one is string , if I enclose that string parameter with single quotes in JSP itself showing this error -
Syntax error on token "someString", invalid AssignmentOperator.
If I enclose with double quotes while calling that function I got this error -
SyntaxError: expected expression, got end of script
Missing Escape '\' character in your code.
Try that code;
$("body").append('<img onclick="removeDynamicColumn(this,\'someString\')" src="css/images/builder/removeTDTR.png"/>');
Try escape \
$("body").append('<img onclick="removeDynamicColumn(this,\'someString\')" src="css/images/builder/removeTDTR.png"/>');
let's assume we have an string in a variable like this:
var param = "somestring"
we can inject this variable to your example, this way:
$("body").append('<img onclick="removeDynamicColumn(this, \'' + param + '\')" src="css/images/builder/removeTDTR.png"/>');
G.L
You need to escape your quote marks.
Try using \ before the ' characters around someString.
\'someString\'
Why bind it like that - if you are using jQuery then you can use a delegated bind and then use data- attributes for your string:
var body = $("body");
// give your image a class and data attribute for your string
body.append('<img src="css/images/builder/removeTDTR.png" data-string="some string" class="click-image">')
// this is delegated bind
body.on('click', '.click-image', function() {
var image = $(this), // your image as a jquery object
someString = image.data('string'); // your string
// do your onclick action here
});

quotation marks within quotation marks syntax [duplicate]

I'm outputting values from a database (it isn't really open to public entry, but it is open to entry by a user at the company -- meaning, I'm not worried about XSS).
I'm trying to output a tag like this:
Click Me
DESCRIPTION is actually a value from the database that is something like this:
Prelim Assess "Mini" Report
I've tried replacing " with \", but no matter what I try, Firefox keeps chopping off my JavaScript call after the space after the word Assess, and it is causing all sorts of issues.
I must bemissing the obvious answer, but for the life of me I can't figure it out.
Anyone care to point out my idiocy?
Here is the entire HTML page (it will be an ASP.NET page eventually, but in order to solve this I took out everything else but the problem code)
<html>
<body>
edit
</body>
</html>
You need to escape the string you are writing out into DoEdit to scrub out the double-quote characters. They are causing the onclick HTML attribute to close prematurely.
Using the JavaScript escape character, \, isn't sufficient in the HTML context. You need to replace the double-quote with the proper XML entity representation, ".
" would work in this particular case, as suggested before me, because of the HTML context.
However, if you want your JavaScript code to be independently escaped for any context, you could opt for the native JavaScript encoding:
' becomes \x27
" becomes \x22
So your onclick would become:DoEdit('Preliminary Assessment \x22Mini\x22');
This would work for example also when passing a JavaScript string as a parameter to another JavaScript method (alert() is an easy test method for this).
I am referring you to the duplicate Stack Overflow question, How do I escape a string inside JavaScript code inside an onClick handler?.
<html>
<body>
edit
</body>
</html>
Should do the trick.
Folks, there is already the unescape function in JavaScript which does the unescaping for \":
<script type="text/javascript">
var str="this is \"good\"";
document.write(unescape(str))
</script>
The problem is that HTML doesn't recognize the escape character. You could work around that by using the single quotes for the HTML attribute and the double quotes for the onclick.
<a href="#" onclick='DoEdit("Preliminary Assessment \"Mini\""); return false;'>edit</a>
This is how I do it, basically str.replace(/[\""]/g, '\\"').
var display = document.getElementById('output');
var str = 'class="whatever-foo__input" id="node-key"';
display.innerHTML = str.replace(/[\""]/g, '\\"');
//will return class=\"whatever-foo__input\" id=\"node-key\"
<span id="output"></span>
If you're assembling the HTML in Java, you can use this nice utility class from Apache commons-lang to do all the escaping correctly:
org.apache.commons.lang.StringEscapeUtils Escapes and unescapes
Strings for Java, Java Script, HTML, XML, and SQL.
Please find in the below code which escapes the single quotes as part of the entered string using a regular expression. It validates if the user-entered string is comma-separated and at the same time it even escapes any single quote(s) entered as part of the string.
In order to escape single quotes, just enter a backward slash followed by a single quote like: \’ as part of the string. I used jQuery validator for this example, and you can use as per your convenience.
Valid String Examples:
'Hello'
'Hello', 'World'
'Hello','World'
'Hello','World',' '
'It\'s my world', 'Can\'t enjoy this without me.', 'Welcome, Guest'
HTML:
<tr>
<td>
<label class="control-label">
String Field:
</label>
<div class="inner-addon right-addon">
<input type="text" id="stringField"
name="stringField"
class="form-control"
autocomplete="off"
data-rule-required="true"
data-msg-required="Cannot be blank."
data-rule-commaSeparatedText="true"
data-msg-commaSeparatedText="Invalid comma separated value(s).">
</div>
</td>
JavaScript:
/**
*
* #param {type} param1
* #param {type} param2
* #param {type} param3
*/
jQuery.validator.addMethod('commaSeparatedText', function(value, element) {
if (value.length === 0) {
return true;
}
var expression = new RegExp("^((')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))(((,)|(,\\s))(')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))*$");
return expression.test(value);
}, 'Invalid comma separated string values.');
I have done a sample one using jQuery
var descr = 'test"inside"outside';
$(function(){
$("#div1").append('Click Me');
});
function DoEdit(desc)
{
alert ( desc );
}
And this works in Internet Explorer and Firefox.
You can copy those two functions (listed below), and use them to escape/unescape all quotes and special characters. You don't have to use jQuery or any other library for this.
function escape(s) {
return ('' + s)
.replace(/\\/g, '\\\\')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\u00A0/g, '\\u00A0')
.replace(/&/g, '\\x26')
.replace(/'/g, '\\x27')
.replace(/"/g, '\\x22')
.replace(/</g, '\\x3C')
.replace(/>/g, '\\x3E');
}
function unescape(s) {
s = ('' + s)
.replace(/\\x3E/g, '>')
.replace(/\\x3C/g, '<')
.replace(/\\x22/g, '"')
.replace(/\\x27/g, "'")
.replace(/\\x26/g, '&')
.replace(/\\u00A0/g, '\u00A0')
.replace(/\\n/g, '\n')
.replace(/\\t/g, '\t');
return s.replace(/\\\\/g, '\\');
}
Escape whitespace as well. It sounds to me like Firefox is assuming three arguments instead of one. is the non-breaking space character. Even if it's not the whole problem, it may still be a good idea.
You need to escape quotes with double backslashes.
This fails (produced by PHP's json_encode):
<script>
var jsonString = '[{"key":"my \"value\" "}]';
var parsedJson = JSON.parse(jsonString);
</script>
This works:
<script>
var jsonString = '[{"key":"my \\"value\\" "}]';
var parsedJson = JSON.parse(jsonString);
</script>
You can use the escape() and unescape() jQuery methods. Like below,
Use escape(str); to escape the string and recover again using unescape(str_esc);.

why won't my variable value pass onto the url

I've spent waaaay too much time trying to make this work. Is there an html/js superstar who can explain why my code isnt working?
var link = '<a href=\"https://system.netsuite.com/app/site/hosting/scriptlet.nl?script=164&deploy=1&custparamso_id='\"+ recordid +\"'>Approve</a>';
Try this:
var link = 'Approve';
If you want "(quotes) inside a string then you should escape them like this
console.log('\"text\"') // will print "text"
the mistake in you code was that you did the escaping outside the quotes
Instead you can also use "(double quotes) directly inside the '(single quote)
edit: additional information
you can use "(double quotes) with or without escaping inside '(single quote) and vice versa. but when using them together you need to escape them
valid statements:
console.log(" 'text' ") // => 'text'
console.log(' "text" ') // => "text"
console.log(" \"text\" ") // => "text"
console.log(' \'text\' ') // => 'text
var link = '<a ... &custparamso_id=' + encodeURIComponent(recordid) + '>Approve</a>';
dont escape the quotes.
it wokrs fine without it
var link = 'Approve';
http://jsfiddle.net/s6Bej/
Shouldn't it be :
var link = 'Approve';
(Note that I removed the first escaped double quote that shouldn't be here, and move the second inside the single quotes.)
You must not escape double quotes when inside single quotes. Neither should you escape single quotes when inside double quotes.
var link = "Approve

Replace Characters from string with javascript

I have a string like (which is a shared path)
\\cnyc12p20005c\mkt$\\XYZ\
I need to replace all \\ with single slash so that I can display it in textbox. Since it's a shared path the starting \\ should not be removed. All others can be removed.
How can I achieve this in JavaScript?
You could do it like this:
var newStr = str.replace(/(.)\\{2}/, "$1\\");
Or this, if you don't like having boobs in your code:
var newStr = "\\" + str.split(/\\{1,2}/).join("\\");
You can use regular expression to achieve this:
var s = '\\\\cnyc12p20005c\\mkt$\\\\XYZ\\';
console.log(s.replace(/.\\\\/g, '\\')); //will output \\cnyc12p20005c\mkt$\XYZ\
Double backslashes are used because backslash is special character and need to be escaped.

Javascript replace query string + with a space

I'm grabbing the query string parameters and trying to do this:
var hello = unescape(helloQueryString);
and it returns:
this+is+the+string
instead of:
this is the string
Works great if %20's were in there, but it's +'s. Any way to decode these properly so they + signs move to be spaces?
Thanks.
The decodeURIComponent function will handle correctly the decoding:
decodeURIComponent("this%20is%20the%20string"); // "this is the string"
Give a look to the following article:
Comparing escape(), encodeURI(), and encodeURIComponent()
Adding this line after would work:
hello = hello.replace( '+', ' ' );

Categories