How to display special html characters properly via javascript - 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);

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')
)

Passing escaped query string with html special chars between two pages

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

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

Textarea \n to <br> without escaping

I am entering stuff in a textarea, and after I press a button, my JS takes the textarea input and puts it inside a div tag.
The problem is, when I enter a newline in the textarea, like so:
Hi
Goodbye
It comes out in the div as
Hi<br><br>Goodbye
When I use Firebug to inspect the actual HTML markup live, I see this in the div:
Hi<br> <br> Goodbye
This is a function I found that should replace the newlines with breaktags:
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '\<br \/>' : '\<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
Here is how I use it:
etext = $('#mytext').val();
etext = nl2br(etext,false);
$('#mydiv').text(etext);
However as you see, it is not working.
How can I do this? If you need more code, do let me know
Perhaps it will work if you do:
$('#mydiv').html(etext);
...or with no framework:
document.getElementById("mydiv").innerHTML = etext;
The problem is that text() is automatically escaping your markup characters:
We need to be aware that this method escapes the string provided as
necessary so that it will render correctly in HTML. To do so, it calls
the DOM method .createTextNode(), which replaces special characters
with their HTML entity equivalents (such as < for <).

JavaScript htmlentities French

I have a .NET MVC page with a list of items that each have
<%: %> encoded descriptions in the rel.
I want to be able to search for all items with a rel that contains my search query.
One of the fields has a value with htmlentities rel='Décoration'
I type "Décoration" in the search box, let jQuery search for all elements that have a 'rel' attribute that contains (indexOf != -1) that value:
no results!
Why? because Décoration != Décoration.
What would be the best solution to compare these two? (Has to work for all special accented characters, not just é)
P.S. (I tried escape/unescape on both sides, also tried the trick to append it to a div and then read it as text, this replaces dangerous stuff, but doesn't replace é (it doesn't have to because it's valid in utf-8 anyway))
Since the é and like are html entities, you can set the html content of a temporary div with the garbled string, and retrive the decoded string using the text content of the element. The browser will do the decoding work for you.
Using jQuery :
function searchInRel(needle) {
return $('[rel]').filter(function(i,e) {
var decodedText = $('<div/>').html(e.attr('rel')).text();
return (decodedText.indexOf(needle) != -1);
};
}
Using just the DOM :
function decodeEntities(text) {
var tempDiv = document.getElementById('tempDiv');
tempDiv.innerHTML = text;
return tempDiv.textContent;
}
If you serve your pages with UTF-8 encoding, you won't need to use entities for all the accented characters. Problem solved.
You can decode the html entities.
Just copy the two javascript methods from HERE
var decoded = 'Décoration';
var entity = html_entity_decode('Décoration');
console.log(decoded == entity);

Categories

Resources