Passing escaped query string with html special chars between two pages - javascript

I'm trying to pass a query string containing special html chars (e.g. <). I have to do
window.location.href = ".."
And on the other page, I have to retrieve this query string using PHP. But when I check it using isset() it returns false!
For example, when i need to escape <p> using JS like this :
function HtmlEncode(s)
{
var el = document.createElement("div");
el.innerText = el.textContent = s;
s = el.innerHTML;
return s;
}
window.location.href = "http://localhost/test.php?t="+HTMLEncode("<p>");
Now the url is: http://localhost/test.php?t=<p>.
When i do echo isset($_GET["t"]);, i get false as a result.
Or even when i try this is a <p> tag, i get $_GET["t"] equals to this is a.
Can anyone tell me what's happening ?

Don't use HTMLEncode() use encodeURIComponent()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Related

How to convert string from ENV to hex in JavaScript? [duplicate]

I have a string in JS in this format:
http\x3a\x2f\x2fwww.url.com
How can I get the decoded string out of this? I tried unescape(), string.decode but it doesn't decode this. If I display that encoded string in the browser it looks fine (http://www.url.com), but I want to manipulate this string before displaying it.
Thanks.
You could write your own replacement method:
String.prototype.decodeEscapeSequence = function() {
return this.replace(/\\x([0-9A-Fa-f]{2})/g, function() {
return String.fromCharCode(parseInt(arguments[1], 16));
});
};
"http\\x3a\\x2f\\x2fwww.example.com".decodeEscapeSequence()
There is nothing to decode here. \xNN is an escape character in JavaScript that denotes the character with code NN. An escape character is simply a way of specifying a string - when it is parsed, it is already "decoded", which is why it displays fine in the browser.
When you do:
var str = 'http\x3a\x2f\x2fwww.url.com';
it is internally stored as http://www.url.com. You can manipulate this directly.
If you already have:
var encodedString = "http\x3a\x2f\x2fwww.url.com";
Then decoding the string manually is unnecessary. The JavaScript interpreter would already be decoding the escape sequences for you, and in fact double-unescaping can cause your script to not work properly with some strings. If, in contrast, you have:
var encodedString = "http\\x3a\\x2f\\x2fwww.url.com";
Those backslashes would be considered escaped (therefore the hex escape sequences remain unencoded), so keep reading.
Easiest way in that case is to use the eval function, which runs its argument as JavaScript code and returns the result:
var decodedString = eval('"' + encodedString + '"');
This works because \x3a is a valid JavaScript string escape code. However, don't do it this way if the string does not come from your server; if so, you would be creating a new security weakness because eval can be used to execute arbitrary JavaScript code.
A better (but less concise) approach would be to use JavaScript's string replace method to create valid JSON, then use the browser's JSON parser to decode the resulting string:
var decodedString = JSON.parse('"' + encodedString.replace(/([^\\]|^)\\x/g, '$1\\u00') + '"');
// or using jQuery
var decodedString = $.parseJSON('"' + encodedString.replace(/([^\\]|^)\\x/g, '$1\\u00') + '"');
You don't need to decode it. You can manipulate it safely as it is:
var str = "http\x3a\x2f\x2fwww.url.com";
​alert(str.charAt(4)); // :
alert("\x3a" === ":"); // true
alert(str.slice(0,7))​; // http://
maybe this helps: http://cass-hacks.com/articles/code/js_url_encode_decode/
function URLDecode (encodedString) {
var output = encodedString;
var binVal, thisString;
var myregexp = /(%[^%]{2})/;
while ((match = myregexp.exec(output)) != null
&& match.length > 1
&& match[1] != '') {
binVal = parseInt(match[1].substr(1),16);
thisString = String.fromCharCode(binVal);
output = output.replace(match[1], thisString);
}
return output;
}
2019
You can use decodeURI or decodeURIComponent and not unescape.
console.log(
decodeURI('http\x3a\x2f\x2fwww.url.com')
)

Javascript remove double quotes from string having forward slash

What I have : I have following string "/.\*n.*/"
What I want : I want to remove double quotes from above string which will look like /.\*n.*/
What I tried :
var filter = "/.\*n.*/";
var modifiedFilter = filter.replace(/"/g, "");
Somehow this code is not working. When I look at modifiedFilter in debug mode, It still shows string with double quotes "/.\*n.*/".
Is it because its a string variable and debug value shows string in double quotes?
But if it is the case, then I am passing this variable to mongodb query and there query is not working due to double quotes.
What am I missing?
// To have quotes in your string, assign it like following:
var filter = '"/.\*n.*/"';
// Your code to remove the quotes is correct.
var modifiedFilter = filter.replace(/"/g, "");
// Verify that the code worked
console.log(filter, modifiedFilter)
It is impossible to remove " from "/.\*n.*/"; in your case as it is required to create strings. It is only possible if "/.\*n.*/"; denotes the actual value of the string and in that case assignment should look like var filter = '"/.\*n.*/"', and this problem will have sense for the answerers.
Just use var modifiedFilter = filter.replace(/\"/g, "").
First have a look at the below statements executed on Node REPL.
> s = "/.\*n.*/"
'/.*n.*/'
>
> s.replace(/'/g, '')
'/.*n.*/'
>
> s = "'/.\*n.*/'"
'\'/.*n.*/\''
>
> s.replace(/'/g, '')
'/.*n.*/'
>
Now have a look at the below code.
var s = '"/.\*n.*/"'
var output = s.replace(/\"/g, "")
console.log(s) // "/.*n.*/"
console.log(output) // /.*n.*/
Your problem here is either with the query, or with attempting to treat a string primitive directly as a regular expression. Instead of trying to remove the (non-existent) speech marks, instead use the RegExp constructor to convert it into a regular expression.
var filter = "/.\*n.*/";
var modifiedFilter = new RegExp(filter).slice(1, -1);
The string needs to be sliced because the RegExp constructor accepts a regular expression without // marks.

parsing image name from img tag with regex

I have an <img> tag inside a div where i want to get the image name through javascript and regex.
Now, I successfully retrieved the <img> tag as a string.
var bigImage = $(this).find('.img-container img')
var bigImageSrc = bigImage[0].src
var regx = /g\bplaceholderdefault\.jpg?\b/g
var match = bigImageSrc.match(regx)
I want this expression to see if there is placeholderdefault.jpg in the string.
By the way, bigImageSrc returns a valid string, as I checked it with typeof
Now the problem is it returns null even if bigImageSrc's value is http://localhost/yogurtbar/images/slider/placeholderdefault.jpg
I don't get why it doesn't detect placeholderdefault.jpg in the string. I tried (and produced) this regular expression in Regexr and it works.
What am I doing wrong in my code?
There is no need of regex.\
You can use indexOf. This will run faster as compared to regex:
if (bigImageSrc.indexOf('placeholderdefault.jpg') > -1) {
// Present
If you want to check it with regex:
if (/placeholderdefault\.jpg/.test(bigImageSrc)) {
// Present
}
You need to escape .
You need to remove the g present at the start.
var regx = /g\bplaceholderdefault\.jpg?\b/g;
^
|
Since there isn't a charcater g exists before p (in placeholder), your regex fails to find a match.
correct one would be,
var regx = /\bplaceholderdefault\.jpg?\b/g;
and also, I think you want to match both jpg and jpeg formats.
var regx = /\bplaceholderdefault\.jpe?g\b/g;
Easy way will be to get the image name using split()
var bigImageSrc = 'http://localhost/yogurtbar/images/slider/placeholder-default.jpg';
var filename = bigImageSrc.split("/").pop();
console.log(filename);
//output placeholder-default.jpg

How to display special html characters properly via javascript

I'm using javascript to get some asp.net server variables to display them, problem is that if the have some html special character the string isn't being assigned as it's on server and it displays wrong.
For example the string :
`ALBERTO GÓMEZ SÁNCHEZ`
is displaying like
`ALBERTO GóMEZ SáNCHEZ`
I know I could use a Replace function but doing that for every possible special html character seems too time consuming... I guess there must be some built-in function that solves that easily but I cannot find it or an easier method than trying to replace every possible html special character.
Do you know any way? Thanks for your help.
If you want to decode html string use this way:
function decodeHTMLEntities (str) {
if(str && typeof str === 'string') {
// strip script/html tags
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
Taken from here: HTML Entity Decode
If you want do put this html string into your DOM, you don't need to decode it, the browser will do this job for you.
Just insert it like this:
$("body").html(encodedHtmlStringFromServer);

replace two same character with whitespace

I am trying to replace the string below with whitespaces using javascript
function replaceString()
{
var str = "ABC**EFG";
return str.replace(/\*/g, " ");
}
I received the result as ABC EFG but I expect the result to come with two whitespace.
I also tried the same thing using php str.replace but still get the same result.
Is there any other methods i can used to replace the individual asterisk with whitespace??
P/S: The return string will be used as part of the sql query
[UPDATE]
I ended up return the string without any replacement to sql, then I use sql replace function to perform replacement in the query.
If you're displaying the resulting string in an HTML element then two or more whitespaces will be displayed as only one whitespace. To workaround this fact, use instead:
return str.replace(/\*/g, ' ');
try this
return str.replace(/\*/g, ' ');
Buddy the problem is with the HTML compiler which has its own special rules of parsing
So it parses multiple spaces into one.This can work for HTML only.
Thats why use the GIFT tag .
<pre>
<p id="para"></p>
</pre>
<script> function replaceString()
{
var str = "ABC**EFG";
return str.replace(/\*/g," ");
}
document.getElementById("para").innerHTML=replaceString();
</script>
<script>
function replaceString()
{ var str1=String.fromCharCode(32,32);
var str = "ABC**EFG";
return str.replace(/\*/g,str1);
}
alert(replaceString());
</script>
return of function from above code can be used directly in mysql...
Finally found the best solution, I replace those special characters using percent-encoding (URL-encoding)
for my case: str.replace(/\*/g, "%20");

Categories

Resources