why won't my variable value pass onto the url - javascript

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

Related

Escaping apostrophe (single quote) character in javascript and html

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 &apos;, ' 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`;

How to prevent html attribute value from generating new line, my json string value breaks

I am inserting a json string value as a value of a button element attribute,
like for example below
var $json = JSON.stringify('{"Long_text":"This is \'my json string and soon..."}');
$("#button_id").attr('data-json', $json);
This works in some of my pages but when there is a single quote in the text even if it is escape with a slash the value in the element attribute creates newline and it breaks
like:
<button data-json="{"Long_text":"This is \' "
"my json string and soon..."}" >Click</button>
I have tried using
replace('/\r?\n|\r|\n/g/',''); //to replace multiple newlines
Even if I replace the double spaces it doesn't work because the attribute itself was malformed. So when I get the attribute and try to parse the json value it cause an error.
I have found this,"->Line break inside HTML tag attribute value" should I replace the spaces with this %0D%0A ? as suggested
to preserved newlines or spaces?
Any help or advise is well appreciated! Thanks!
I found a solution other than replacing the spaces with this %0D%0A
from this Line break inside HTML tag attribute value
var base64 =
{
encode: function utoa(str)
{
return window.btoa(unescape(encodeURIComponent(str)));
},
decode: function atou(str)
{
return decodeURIComponent(escape(window.atob(str)));
}
}
I tried this and it works, it also make the string non-readable since it is base64_encoded, it avoid the line breaks caused by spaces and quotes.
var $json = base64.encode(JSON.stringify('{"Long_text":"This is \'my json string and soon..."}'));
$("#button_id").attr('data-json', $json);
then get the value and convert it again,
var valid_json = JSON.parse(base64.decode($("#button_id").attr('data-json')));
Thanks!

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
});

Split with this char : "\"

I have a problem with the .split() function , I have the following string:
var imageUrl = "Images\Products\randomImage.jpg";
And I want to split by the character "\", but, this happens:
//If dont use double "\\", throws me an error.
var imageUrlArray = imageUrl.split("\\");
Then the variable has this value:
"ImagesProductsrandoImage.jpg"
I need to do that, because need to change this "\" into "/", because makes me an error with a plugin. The original String is obtained from the DataBase.
The first \ is escaping the second \ character. Your string should also be doubled up.
var imageUrl = "Images\\Products\\randomImage.jpg";
var updated = imageUrl.replace(/\\/g,"/");
console.log(updated);
You need to escape the file string so that the backslashes there become "\", then you can preform your split, and then un-escape the resulting array of strings for other characters that may have been backslashed.
Not too familiar with Javascript but it probably looks something like this:
$fileName = escape($fileName)

Escaping single quotes in JavaScript string for JavaScript evaluation

I have a project, in which some JavaScript var is evaluated. Because the string needs to be escaped (single quotes only), I have written the exact same code in a test function. I have the following bit of pretty simple JavaScript code:
function testEscape() {
var strResult = "";
var strInputString = "fsdsd'4565sd";
// Here, the string needs to be escaped for single quotes for the eval
// to work as is. The following does NOT work! Help!
strInputString.replace(/'/g, "''");
var strTest = "strResult = '" + strInputString + "';";
eval(strTest);
alert(strResult);
}
And I want to alert it, saying: fsdsd'4565sd.
The thing is that .replace() does not modify the string itself, so you should write something like:
strInputString = strInputString.replace(...
It also seems like you're not doing character escaping correctly. The following worked for me:
strInputString = strInputString.replace(/'/g, "\\'");
Best to use JSON.stringify() to cover all your bases, like backslashes and other special characters. Here's your original function with that in place instead of modifying strInputString:
function testEscape() {
var strResult = "";
var strInputString = "fsdsd'4565sd";
var strTest = "strResult = " + JSON.stringify(strInputString) + ";";
eval(strTest);
alert(strResult);
}
(This way your strInputString could be something like \\\'\"'"''\\abc'\ and it will still work fine.)
Note that it adds its own surrounding double-quotes, so you don't need to include single quotes anymore.
I agree that this var formattedString = string.replace(/'/g, "\\'"); works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.
The solution that worked for me is that you need to put three \ and escape the double quotes.
"var string = \"l'avancement\";
var formattedString = string.replace(/'/g, \"\\\'\");"
I answer that question since I had trouble finding that three \ was the work around.
Only this worked for me:
searchKeyword.replace(/'/g, "\\\'");//searchKeyword contains "d'av"
So, the result variable will contain "d\'av".
I don't know why with the RegEx didn't work, maybe because of the JS framework that I'm using (Backbone.js)
That worked for me.
string address=senderAddress.Replace("'", "\\'");
There are two ways to escaping the single quote in JavaScript.
1- Use double-quote or backticks to enclose the string.
Example: "fsdsd'4565sd" or `fsdsd'4565sd`.
2- Use backslash before any special character, In our case is the single quote
Example:strInputString = strInputString.replace(/ ' /g, " \\' ");
Note: use a double backslash.
Both methods work for me.
var str ="fsdsd'4565sd";
str.replace(/'/g,"'")
This worked for me. Kindly try this
The regular expression in the following code also handles the possibility of escaped single quotes in the string - it will only prepend backslashes to single quotes that are not already escaped:
strInputString = strInputString.replace(/(?<!\\)'/g, "\\'");
Demo: https://regex101.com/r/L1lF7J/1
Compatibility
The regex above uses negative lookbehind, which is widely supported but if using an older Javascript version, this clunkier regex (which uses a capturing group backreference instead) will also do the job:
strInputString = strInputString.replace(/(^|[^\\])'/g, "$1\\'");
Demo: https://regex101.com/r/9niyYw/1
strInputString = strInputString.replace(/'/g, "''");

Categories