I understand that JavaScript (the language that implements the spec) is case sensitive. For example, variable names:
let myVar = 1
let MyVar = 2 // different :)
I haven't been able to find anything in the spec itself that indicates that this is a requirement, so I'm not sure if that was just a design decision independent of the spec.
I think I found something that specifies this. Names and Keywords says:
Two IdentifierNames that are canonically equivalent according to the Unicode standard are not equal unless, after replacement of each UnicodeEscapeSequence, they are represented by the exact same sequence of code points.
Since uppercase and lowercase letters have different code points, identifiers with different case are not equal.
Yes it is case sensitive but generally JavaScript developers follow camel case convention.
Related
doucument.getElementById("xyz").value;
this this statement why we write get in small and element word staring form capital word E same as B And I
It's called Camel Case and it's just a styling/naming convention
It's called lowerCamelCase. This is just writing style.
Java naming convention dictates the following: "Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized." - from https://www.oracle.com/technetwork/java/codeconventions-135099.html
So in short, it's like that because convention dictates it should be.
Because as it called camelCase and it is one of the Javascript coding conventions, here's a list of other style Coding Conventions from w3school.
js_conventions
Can i write something like this
class Person{
testMethod(){
return true;
}
}
var People = new Person();
console.log(People.testMethod());
can i initialize with Capital Letter for class instance ?
Yes, you can. But it is not a standard way of naming your instance variables as it makes readability poor. If a third person reads your code, he/she would like to expect the Class names starting with Capital letters and instance variables with small letters.
Here is a list of naming conventions that should be followed as a good practice. https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Coding_Style
Yes you can! But the standard in Javascript is that capital letter are for Classes or constructor functions! And camel case for variables and functions!
I really recommend you to use ESlint to force you to follow some code style! Also I recommend Standard JS rules: https://standardjs.com/ (probably the most used code style)
Class name conventions
Class, interface, record, and typedef names are written in UpperCamelCase. Unexported classes are simply locals: they are not marked #private and therefore are not named with a trailing underscore.
Type names are typically nouns or noun phrases. For example, Request, ImmutableList, or VisibilityMode. Additionally, interface names may sometimes be adjectives or adjective phrases instead (for example, Readable).
Rules common to all identifiers -
Identifiers use only ASCII letters and digits, and, in a small number of cases noted below, underscores and very rarely (when required by frameworks like Angular) dollar signs.
Give as descriptive a name as possible, within reason. Do not worry about saving horizontal space as it is far more important to make your code immediately understandable by a new reader. Do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word.
priceCountReader // No abbreviation.
numErrors // "num" is a widespread convention.
numDnsConnections // Most people know what "DNS" stands for.
n // Meaningless.
nErr // Ambiguous abbreviation.
nCompConns // Ambiguous abbreviation.
wgcConnections // Only your group knows what this stands for.
pcReader // Lots of things can be abbreviated "pc".
cstmrId // Deletes internal letters.
kSecondsPerDay // Do not use Hungarian notation.
If this exact question has been asked before, please point me to the relevant question.
tl;dr: How does one compare two strings in JavaScript while ignoring casing according to English rules?
My code analyzes and compares data from two different sources, each with different opinions about whether keywords should be upper or lower case, meaning that a case-insensitive comparison is required. However, I don't want the system to break if used in other cultures (such as Turkey and its notorious problems with the letter I).
Does JavaScript have any way of doing a culture-independent (read: English) case-insensitive string comparison?
How does one compare two strings in JavaScript without breaking if used in other cultures (such as Turkey and its notorious problems with the letter I)? Does JavaScript have any way of doing a culture-independent case-insensitive string comparison?
Yes, by simply using the standard .toLowerCase method which is not affected by locale settings. a.toLowerCase() == b.toLowerCase() is perfectly fine. The spec even mandates:
The result must be derived according to the case mappings in the Unicode character database
This definitely is consistent across all systems regardless of their settings.
For respecting the current locale, you would use .toLocaleLowerCase explicitly. MDN states:
In most cases, this will produce the same result as toLowerCase(), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result.
However, relying on locales does not seem to work well…
In theory there is a method for that: String.localCompare().
The problem is that it's not implemented correctly by most browsers.
You might have more luck using String.toLocaleLowerCase().
Example:
if ("Äpfel".toLocaleLowerCase() == "äpfel".toLocaleLowerCase()) alert("Case Insensitive Match")
Be aware that following will not match (because ä and a are different characters):
if ("Äpfel".toLocaleLowerCase() == "apfel".toLocaleLowerCase()) alert("Case Insensitive Match")
You can use localeCompare but be aware that it is implemented differently between browsers. What seems to work in Chrome/Firefox/IE11 is:
first.localeCompare("First", navigator.language, { sensitivity: "base" }) === 0
var console = function() {
var log = function(message) {
strMessage = "<p>" + message + "</p>";
$("#console").append(strMessage);
};
return {
log: log
};
}()
var first = "first";
var result = first.localeCompare("First", navigator.language, { sensitivity: "base" }) === 0;
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="console">
</div>
I'm running over all textnodes of my DOM and check if the nodeValue contains a certain string.
/html/body//text()[contains(.,'test')]
This is case sensitive. However, I also want to catch Test, TEST or TesT. Is that possible with XPath (in JavaScript)?
This is for XPath 1.0. If your environment supports XPath 2.0, see here.
Yes. Possible, but not beautiful.
/html/body//text()[
contains(
translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),
'test'
)
]
This would work for search strings where the alphabet is known beforehand. Add any accented characters you expect to see.
If you can, mark the text that interests you with some other means, like enclosing it in a <span> that has a certain class while building the HTML. Such things are much easier to locate with XPath than substrings in the element text.
If that's not an option, you can let JavaScript (or any other host language that you are using to execute XPath) help you with building an dynamic XPath expression:
function xpathPrepare(xpath, searchString) {
return xpath.replace("$u", searchString.toUpperCase())
.replace("$l", searchString.toLowerCase())
.replace("$s", searchString.toLowerCase());
}
xp = xpathPrepare("//text()[contains(translate(., '$u', '$l'), '$s')]", "Test");
// -> "//text()[contains(translate(., 'TEST', 'test'), 'test')]"
(Hat tip to #KirillPolishchuk's answer - of course you only need to translate those characters you're actually searching for.)
This approach would work for any search string whatsoever, without requiring prior knowledge of the alphabet, which is a big plus.
Both of the methods above fail when search strings can contain single quotes, in which case things get more complicated.
XPath 2.0 Solutions
Use lower-case():
/html/body//text()[contains(lower-case(.),'test')]
Use matches() regex matching with its case-insensitive
flag:
/html/body//text()[matches(.,'test', 'i')]
Case-insensitive contains
/html/body//text()[contains(translate(., 'EST', 'est'), 'test')]
Yes. You can use translate to convert the text you want to match to lower case as follows:
/html/body//text()[contains(translate(.,
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz'),
'test')]
The way i always did this was by using the "translate" function in XPath. I won't say its very pretty but it works correctly.
/html/body//text()[contains(translate(.,'abcdefghijklmnopqrstuvwxyz',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'),'TEST')]
hope this helps,
If you're using XPath 2.0 then you can specify a collation as the third argument to contains(). However, collation URIs are not standardized so the details depend on the product that you are using.
Note that the solutions given earlier using translate() all assume that you are only using the 26-letter English alphabet.
UPDATE: XPath 3.1 defines a standard collation URI for case-blind matching.
We're all familiar with naming conventions in R (if not: Venables & Smith - Introduction to R, Chapter 1.8). Regular expressions, on the other hand, remain terra incognita and the most hated part in my programming life so far ... Recently, I've officially started JavaScript recapitulation, and I'm trying to create precise RegExp to check correct R object name.
Brief intro:
Object names must start with . or lower/uppercase letter, and if they start with . cannot continue with numeric... afterward, alphanumeric symbols are allowed with . and underscore _.
Long story short, here's my JS code:
var txt = "._.";
var inc = /^\.(?!\d)|^[a-z\.]/i;
document.write(inc.test(txt));
This approach manages the first part (. and/or lower/upper case and numeric after .), but I cannot pass something like & [\w\.]. I can write a function that will take care of this one, but is it at all possible to manage this with a single RegExp?
I'm not familiar with R or its naming conventions, but I'll give it a shot:
If you're only trying to verify that the name begins correctly, all you need to do is remove the \. from the character class, leaving you with: /^\.(?!\d)|^[a-z]/i. Otherwise, the . may still be the first character with no restrictions on the remaining ones.
If you want to verify the that entire name is correct, something like this should work:
/^(?:\.(?!\d)|[a-z])[a-z0-9_\.]+$/i