I want to escape javascript entities on client side. For example :-
If my input string is tes"t result should be tes\"t
Is there any inbuilt function provided by jquery for this ?
This is a really crazy, almost stupid shot in the dark on my part, but...
If you're using a server-side language like PHP to output variables' contents into JavaScript, you should use json_encode as this handles ALL escaping for you, regardless of the type of variable.
On the other hand, if you're (I really hope you're not) doing something like this:
var input = "test"t";
And trying to escape that properly while in JavaScript... that's not going to work. It's a syntax error. You need to escape your literals manually.
Kevin van Zonneveld provide a JavaScript equivalent of PHP’s addslashes here :
http://phpjs.org/functions/addslashes/
function addslashes(str) {
// example 1: addslashes("kevin's birthday");
// returns 1: "kevin\\'s birthday"
return (str + '')
.replace(/[\\"']/g, '\\$&')
.replace(/\u0000/g, '\\0');
}
Based on this function, I guess you might want to add this function to prototype of the String like this.
if (!String.prototype.addslashes) {
String.prototype.addslashes = function () {
return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
};
}
var str = 'tes"t';
alert(str.addslashes()); // shows 'tes\"t'
DEMO: http://jsfiddle.net/naokiota/6F6aN/6/
Hope this helps.
Related
I have the following javascript code that attempts to insert HTML code dynamically. I have an error the syntax but I do not know how to correct it. Please can someone advise?
loadNextContainer.innerHTML = '<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords(\''+numDownloadSoFar+'\', \''+maxDownloadLimit+'\', \''+folderName+'\', \''+jsonHashTags+'\', \''+fromDate+'\', \''+toDate+'\', \''+lastScanId+'\')">LoadNext</span>';
ERROR MESSAGE:
Uncaught SyntaxError: Invalid or unexpected token
I believe the error revovles around the function variables. In particular the JSON variable. I cannot change the use of double quotation marks for each element in the JSON. So that has to stay in any solution.
You could try it using backticks like this.
loadNextContainer.innerHTML = `<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords('`+numDownloadSoFar+`', '`+maxDownloadLimit+`', '`+folderName+`', '`+jsonHashTags+`', '`+fromDate+`', '`+toDate+`', '`+lastScanId+`')">LoadNext</span>';
Or just escape the double-quotes instead of the single quotes. The way you're doing it, you're unintentionally opening up the string when you try to escape it.
loadNextContainer.innerHTML = "<span class=\"sr_43\" id=\"srloadnext_2\" onclick=\"srt.loadNextMatchRecords('"+numDownloadSoFar+"', '"+maxDownloadLimit+"', '"+folderName+"', '"+jsonHashTags+"', '"+fromDate+"', '"+toDate+"', '"+lastScanId+"')\">LoadNext</span>";
Judging from your image of your variables, none of the template literal solutions are going to help you, because at least one of your parameters is an array.
Yes, it would be possible, with enough effort, to convert that array into a string representation that would work with innerHTML. But it's going to be very difficult. You'd end up needing to use JSON.stringify to get the string version of your array at least.
An easier solution is actually going to be to create the element and then add the onclick operator through pure javascript, like this:
var s = document.createElement('span');
s.className = 'sr_43';
s.id = 'srloadnext_2';
s.innerText = 'LoadNext';
loadNextContainer.appendChild(s);
s.onclick = function(e) {
srt.loadNextMatchRecords(numDownloadSoFar, maxDownloadLimit, folderName, jsonHashTags, fromDate, toDate, lastScanId);
};
Try it with template literals:
loadNextContainer.innerHTML = `<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords(\'${numDownloadSoFar}\', \'${maxDownloadLimit}\', \'${folderName}\', \'${jsonHashTags}\', \'${fromDate}\', \'${toDate}\', \'${lastScanId}\')">LoadNext</span>`;
Edit:
As others already mentioned. Sorry.
How can I strip the $ and , characters from the following value, the code i am using is not working
var asset_value = second_col.find("input[type=text]").val().replace('$', '');
second_col.find("input[type=text]").val() looks like
$1,080.00
Update:
I am not sure why i am getting voted down! the duplicate solution does not solve my question, nor does any answer below, except for this, very strange!
second_col.find("input[type=text]").val(function(i, val) {
return val.replace(/\$|,/g, '');
});
var asset_value = second_col.find("input[type=text]").val();
You can use regex for this:
second_col.find("input[type=text]").val().replace(/[\$,]/g,'').
Assign this value to variable and use it.
I have a JS function which is generated by some PHP, the function call is below:
onClick=openPopup('".$row['imgname']."','".$row['adtitle']."','".$row['adviews']."')
Now this works unless the value of $row['adtitle'] contains a JS keyword. The one that brought the bug in my code to my attention was the word 'THIS'. Would there be a way to escape these values, I can't figure it out as I have already used a lot of encapsulation in this call.
Thanks in advance.
EDIT:
openPopup('efc86f7223790e91f423ef1b73278435.jpg','THIS IS A TEST ADVERT 12345678','2')
This call does not work.
openPopup('eada91a6c1197d2f2320e59f45d8ca6b.jpg','is a test','2')
however this one does work..
only thing I could figure was the THIS as when looking at the source, the text following THIS is highlighed differently.
Edit 2 : Here is my function:
function openPopup(imgname,adtitle,adviews) {
document.getElementById('popup').style.display = 'block';
document.getElementById('delimg').src = 'imgstore/' + imgname;
document.getElementById('delAdTitle').innerHTML = adtitle;
document.getElementById('delAdViews').innerHTML = adviews;
document.getElementById('confirm').onclick = function() {
location.href = '?delete=1&id=' + imgname;
}
}
Maybe it’s just a question of proper formatting:
$onclick = 'openPopup('.json_encode($row['imgname']).','.json_encode($row['adtitle']).','.json_encode($row['adviews']).')';
echo 'onClick="'.htmlspecialchars($onclick).'"';
Note that we’re abusing json_encode here to quote the JavaScript string literals. Although we shouldn’t as strictly speaking JSON strings are not a subset of JavaScript strings.
I am trying to make a function with regular expression [javascript].
Please take a look.
function ReplaceIt(key)
{
var KeyCode = /.body\s*\{([^\}]*?)\}/m; // i want to replace the body to the key
}
var key ="h1";
ReplaceIt(key);
so the final result will be
var Keycode = /.h1\s*\{([^\}]*?)\}/m;
I am little bit newbie with javascript and I don't know how to search other resources.
Note: Friends, why are you deleting the answers?? Each and every comment/answer is helping us to improve, but we will choose the most appropriate/best answer, please don't delete comments/answers.
You can use RegExp with a string to build up your regular expression. If you build the regular expression that way, you should escape all '\'. So your function could look like:
function ReplaceIt(key)
{
return RegExp('.'+key+'\\s*\\{([^\\}]*?)\\}','m');
}
var reKey = ReplaceIt('h1'); //=> /.h1\s*\{([^\}]*?)\}/m
I am trying a new direction in Language Kits (or whatever you want to call those multi language text files with placeholders). Basically, I have text like this: Hello, my name is %0. Welcome to %1!. This would be my pText.
My pValues is an array whose values represent %0 and %1.
The following function should find %0 and replace it with pValues[0] and so on.
function _parseDialogMessage(pText, pValues) {
var result = pText;
for (var i=0; i<pValues.length; ++i) {
var regex = new RegExp('\%'+i, 'gi');
pText = pText.replace(regex, pValues[i]);
}
return result;
}
It all works except for the fact that it does not replace the placeholders %0 and %1. All Variables have the expected values but .replace doesn't seem to find my placeholders.
Any help?
Edit 1
Shame on me... -.-
You don't need "dynamic regex", since replace can take a function as argument:
function _parseDialogMessage(pText, pValues) {
return pText.replace(/%(\d+)/g, function (s, i) { return pValues[i]; });
}
(and you should return pText.)
You are returning the result variable which hold the initial values of the ptext parameter..
return the pText variable..
UUhm, you return result and not the replace pText
While you can't use any of their code unless you want to GPL your library, the manual for gnu's gettext covers the rationale behind a number of topics related to internationalization.
http://www.gnu.org/software/gettext/manual/gettext.html
edit : I know you're just looking for a magic regex, but it won't be enough.
easy example :
I have %n computers.
I have 1 computers.
Did you know arabic has a special tense for 2 things, and chinese no tense for the number of things referred to?