I'm designing chess board in HTML. ♖ is the code to display the WHITE ROOK.
I'm trying to set the value while page loads and it is displaying it as a string, but the ROOK is not coming on the button
function load() {
document.getElementById('A1').value="♖";
}
function load() {
document.getElementById('A1').innerHTML="♖";
}
http://jsfiddle.net/RM5VD/2/
The notation ♖ or ♖ has no special meaning in JavaScript; they are just strings of characters, though these strings can be assigned to the innerHTML property, causing HTML parsing.
The simplest way use a Unicode character in JavaScript to insert it as such, though this requires a suitable editor and the use of the UTF-8 character encoding. Example:
document.getElementById('A1').value = '♖';
The next simplest is to use the JavaScript escape notation, namely \u followed by exactly four hexadecimal digits. Since WHITE CHESS ROOK is U+2656 (2656 hex = 9815 decimal), you would use this:
document.getElementById('A1').value="\u2656";
This makes sense only if the element modified has the value property as per HTML specs. For example, <input type=button> has it, but button doesn’t. But this affects just the left hand of the assignment, i.e. what you assign the string to.
Beware that font support to chess piece characters like this is rather limited. Moreover, browsers may have their own ideas of the font to be used in buttons. In practice, you should probably use some downloadable font.
You need to rewrite the function like this:
function load() {
document.getElementById('A1').value=String.fromCharCode(9814);
}
It's not clear exactly what kind of element you're modifying, but you may need to modify the innerHTML instead of the value depending on your situation.
The way you have it, it is passing the text as a literal string, not a representation of a single character.
jsFiddle example
Related
I use a regex for my splitfunction.
string.split(/\s/)
But (which is a Hair Space), will not be recognised. How to make sure it does (without implementing the exact code in the regex expression)
Per MDN, the definition of \s in a regex (in the Firefox browser) is this:
[ \f\n\r\t\v\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]
So, if you want to split on something in addition to this (e.g. an HTML entity), then you will need to add that to your own regex. Remember, string.split() is not an HTML function, it's a string function so it doesn't know anything special about HTML. If you want to split on certain HTML tags or entities, you will have to code up a regex that includes the things you want to split on.
You can code for it yourself like this:
string.split(/\s| /);
Working demo: http://jsfiddle.net/jfriend00/nAQ97/
If what you really want to do is to have your HTML parsed and converted to text by the browser (which will process all entities and HTML tags), then you can do this:
function getPlainText(str) {
var x = document.createElement("div");
x.innerHTML = str;
return (x.textContent || x.innerText);
}
Then, you could split your string like this:
getPlainText(str).split(/\s/);
Working demo: http://jsfiddle.net/jfriend00/KR2aa/
If you want to make absolutely sure this works in older browsers, you'd either have to test one of these above functions in all browsers that you care about or you'd have to use a custom regex with all the entities you want to split on in the first option or do a search/replace on all unicode characters that you want to split on in the second option and turn them into a regular space before doing the split. Because older browsers weren't very consistent here, there is no free lunch if you want safe compatibility with old browsers.
I need to extract a HTML-Substring with JS which is position dependent. I store special characters HTML-encoded.
For example:
HTML
<div id="test"><p>lösen & grüßen</p></div>
Text
lösen & grüßen
My problem lies in the JS-part, for example when I try to extract the fragment
lö, which has the HTML-dependent starting position of 3 and the end position of 9 inside the <div> block. JS seems to convert some special characters internally so that the count from 3 to 9 is wrongly interpreted as "lösen " and not "lö". Other special characters like the & are not affected by this.
So my question is, if someone knows why JS is behaving in that way? Characters like ä or ö are being converted while characters like & or are plain. Is there any possibility to avoid this conversion?
I've set up a fiddle to demonstrate this: JSFiddle
Thanks for any help!
EDIT:
Maybe I've explained it a bit confusing, sorry for that. What I want is the HTML:
<p>lösen & grüßen</p> .
Every special character should be unconverted, except the HTML-Tags. Like in the HTML above.
But JS converts the ö or ü into ö or ü automatically, what I need to avoid.
That's because the browser (and not JavaScript) turns entities that don't need to be escaped in HTML into their respective Unicode characters (e.g. it skips &, < and >).
So by the time you inspect .innerHTML, it no longer contains exactly what was in the original page source; you could reverse this process, but it involves the full map of character <-> entity pairs which is just not practical.
If i understand you correctly, then try use innerHTML or .html('your html code') for jQuery on the target element
We're allowing users to upload pictures and provide a text description. Users can view this through a pop up box (actually a div ) via javascript. The uploaded text is a parameter to a javascript function. I 'm worried about XSS and also finding issues with HTMLEncode().
We're using HTMLEncode to guard against XSS. Unfortunately, we're finding that HTMLEncode() only replaces '<' and '>'. We also need to replace single and double quotes that people may include. Is there a single function that will do all these special type characters or must we do that manually via .NET string.Replace()?
Unfortunately, we're finding that HTMLEncode() only replaces '<' and '>'.
Assuming you are talking about HttpServerUtility.HtmlEncode, that does encode the double-quote character. It also encodes as character references the range U+0080 to U+00FF, for some reason.
What it doesn't encode is the single quote. Bit of a shame but you can usually work around it by using only double quotes as attribute value delimiters in your HTML/XML. In that case, HtmlEncode is enough to prevent HTML-injection.
However, javascript is in your tags, and HtmlEncode is decidedly not enough to escape content to go in a JavaScript string literal. JavaScript-encoding is a different thing to HTML-encoding, so if that's the reason you're worried about the single quote then you need to employ a JS string encoder instead.
(A JSON encoder is a good start for that, but you would want to ensure it encodes the U+2028 and U+2029 characters which are, annoyingly, valid in JSON but not in JavaScript. Also you might well need some variety of HTML-escaping on top of that, if you have JavaScript in an HTML context. This can get hairy; it's usually better to avoid these problems by hiding the content you want in plain HTML, for example in a hidden input or custom attribute, where you can use standard HTML-escaping, and then read that data from the DOM in JS.)
If the text description is embedded inside a JavaScript string literal, then to prevent XSS, you will need to escape special characters such as quotes, backslashes, and newlines. The HttpUtility.HtmlEncode method is not suitable for this task.
If the JavaScript string literal is in turn embedded inside HTML (for example, in an attribute), then you will need to apply HTML encoding as well, on top of the JavaScript escaping.
You can use Microsoft's Anti-Cross Site Scripting library to perform the necessary escaping and encoding, but I recommend that you try to avoid doing this yourself. For example, if you're using WebForms, consider using an <asp:HiddenField> control: Set its Value property (which will be HTML-encoded automatically) in your server-side code, and access its value property from client-side code.
how about you htmlencode all of the input with this extended function:
private string HtmlEncode(string text)
{
char[] chars = HttpUtility.HtmlEncode(text).ToCharArray();
StringBuilder result = new StringBuilder(text.Length + (int)(text.Length * 0.1));
foreach (char c in chars)
{
int value = Convert.ToInt32(c);
if (value > 127)
result.AppendFormat("&#{0};", value);
else
result.Append(c);
}
return result.ToString();
}
this function will convert all non-english characters, symbols, quotes, etc to html-entities..
try it out and let me know if this helps..
If you're using ASP.NET MVC2 or ASP.NET 4 you can replace <%= with <%: to encode your output. It's safe to use for everything it seems (like HTML Helpers).
There is a good write up of this here: New <%: %> Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC 2)
If I just put in XUL file
<label value="°C"/>
it works fine. However, I need to assing ° value to that label element and it doesn't show degree symbol, instead literal value.
UPD
sorry guys, I just missed couple words here - it doesn't work from within javascript - if I assign mylablel.value = degree + "°" - this will show literal value.
It does show degree symbol only if I put above manually in XUL file.
What happens when you use a JavaScript escape, like "\u00B0C", instead of "°C"?
Or when using mylabel.innerHTML instead of mylabel.value? (According to MDC, this should be possible.)
EDIT: you can convert those entities to JavaScript escapes using the Unicode Code Converter.
This makes sense to me. When you express the entity in an attribute value within XML markup, the XML parser interpolates the entity reference and then sets the label value to the result. From Javascript, however, there's no XML parser to do that work for you, and in fact life would be pretty nasty if there were! Note that when you set the value attribute (from Javascript) of an <input type='text'> element, you don't have to worry about having to escape XML entities (or even angle brackets, for that matter). However, you do have to worry about XML entities when you're setting the "value" attribute within XML markup.
Another way to think about it is this: XML entity notation is XML syntax, not Javascript syntax. In Javascript, you can produce special characters using 16-bit Unicode escape sequences, which look like \u followed by a four-digit hex constant. As noted in Marcel Korpel's answer, if you know what Unicode value is produced by the XML entity, then you should be able to use that directly from Javascript. In this case, you could use "\u00B0".
This way it will not work ,can you convert it to be like this
<label>°C</label>
I'm starting to learn some javascript and understand that dashes are not permitted when naming identifiers. However, in CSS it's common to use a dash for IDs and classes.
Does using a dash in CSS interfere with javascript interaction somehow? For instance if I were to use getElementByID("css-dash-name"). I've tried a few examples using getElementByID with dashes as a name for a div ID and it worked, but I'm not sure if that's the case in all other contexts.
Having dashes and underscores in the ID (or class name if you select by that) that won't have any negative effect, it's safe to use them. You just can't do something like:
var some-element = document.getElementByID('css-dash-name');
The above example is going to error out because there is a dash in the variable you're assigning the element to.
The following would be fine though since the variable doesn't contain a dash:
var someElement = document.getElementByID('css-dash-name');
That naming limitation only exists for the javascript variables themselves.
It's only in the cases where you can access the elements as properties that it makes a difference. For example form fields:
<form>
<input type="text" name="go-figure" />
<input type="button" value="Eat me!" onclick="...">
</form>
In the onclick event you can't access the text box as a property, as the dash is interpreted as minus in Javascript:
onclick="this.form.go-figure.value='Ouch!';"
But you can still access it using a string:
onclick="this.form['go-figure'].value='Ouch!';"
Whenever you have to address a CSS property as a JavaScript variable name, CamelCase is the official way to go.
element.style.backgroundColor = "#FFFFFF";
You will never be in the situation to have to address a element's ID as a variable name. It will always be in a string, so
document.getElementById("my-id");
will always work.
Using Hypen (or dash) is OK
I too is currently studying JavaScript, and as far as I read David Flanagan's book (JavaScript: The Definitive Guide, 5th Edition) — I suggest you read it. It doesn't warn me anything about the use of hypen or dash (-) in IDs and Classes (even the Name attribute) in an HTML document.
Just as what Parrots already said, hypens are not allowed in variables, because the JavaScript interpreter will treat it as a minus and/or a negative sign; but to use it on strings, is pretty much ok.
Like what Parrots and Guffa said, you can use the following ...
[ ] (square brackets)
'' (single quotation marks or single quotes)
"" (double quotation marks or double quotes)
to tell the JavaScript interpreter that your are declaring strings (the id/class/name of your elements for instance).
Use Hyphen (or dash) — for 'Consistency'
#KP, that would be ok if he is using HTML 4.1 or earlier, but if he is using any versions of XHTML (.e.g., XHTML 1.0), then that cannot be possible, because XHTML syntax prohibits uppercase (except the !DOCTYPE, which is the only thing that needs to declared in uppercase).
#Choy, if you're using HTML 4.1 or earlier, going to either camelCase or PascalCase will not be a problem. Although, for consistency's sake as to how CSS use separators (it uses hypen or dash), I suggest following its rule. It will be much more convinient for you to code your HTML and CSS alike. And moreoever, you don't even have to worry if you're using XHTML or HTML.
IDs are allowed to contain hyphens:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
And there is no restriction when using IDs in JavaScript except if you want to refer to elements in the global scope. There you need to use:
window['css-dash-name']
Other answers are correct as far as where you can and can't use hyphens, however at the root of the question, you should consider the idea of not using dashes/hyphens in your variable/class/ID names altogether. It's not standard practice, even if it does work and requires careful coding to make use of it.
Consider using either PascalCase (all words begin in capital) or camelCase (first word begins in lowercase, following words being in uppercase). These are the two most common, accepted naming conventions.
Different resources will recommend different choices between the two (with the exception of JavaScript which is pretty much always recommended camelCase). In the end as long as you are consistent in your approach, this is the most important part. Using camel or Pascal case will ensure you don't have to worry about special accessors or brackets in your code.
For JavaScript conventions, try this question/discussion:
javascript naming conventions
Here's another great discussion of conventions for CSS, Html elements, etc:
What's the best way to name IDs and classes in CSS and HTML?
It would cause an error in this case:
const fontSize = element.style.font-size;
Because including a hyphen prevents the property from being accessed via the dot operator. The JavaScript parser would see the hyphen as a subtraction operator. Correct way would be:
const fontSize = element.style['font-size']
No, this won't cause an issue. You're accessing the ID as a string (it's enclosed in quotes), so the dash poses no problem. However, I would suggest not using document.getElementById("css-dash-name"), and instead using jQuery, so you can do:
$("#css-dash-name");
Which is much clearer. the jQuery documentation is also quite good. It's a web developers best friend.