JavaScript Tutorial/String/String comparisons
Содержание
Compare two strings
<HTML>
<BODY>
<SCRIPT language="JavaScript">
<!--
var myVar="AA";
if(myVar=="AA") {
window.alert("AA");
} else {
window.alert("Not AA");
}
//-->
</SCRIPT>
</BODY>
</HTML>
localeCompare
localeCompare() helps sort string values
localeCompare() method takes the string to compare to.
localeCompare() returns one of three values:
If the String object comes alphabetically before the string argument, a negative number is returned.
If the String object is equal to the string argument, 0 is returned.
If the String object comes alphabetically after the string argument, a positive number is returned.
var oStringObject = new String("yellow");
alert(oStringObject.localeCompare("brick")); //outputs "1"
alert(oStringObject.localeCompare("yellow")); //outputs "0"
alert(oStringObject.localeCompare ("zoo")); //outputs "-1"
String comparisons
<html>
<head>
<title>String comparisons</title>
<script type="text/javascript" language="javascript">
<!-- //
onload = function(){
var firstString = new String("AAA");
var secondString = new String("aaA");
document.write("<h3>Direct comparison of the two strings</h3>");
var comparison = (firstString==secondString);
document.write(comparison);
}
// -->
</script>
</head>
<body>
</body>
</html>
String comparisons by converting strings to its uppercase form
<html>
<head>
<title>String comparisons</title>
<script type="text/javascript" language="javascript">
<!-- //
onload = function(){
var firstString = new String("AAA");
var secondString = new String("aaA");
document.write("<h3>Comparison after conversion to upper case</h3>");
var firstUpperString = firstString.toUpperCase();
var secondUpperString = secondString.toUpperCase();
document.write((firstUpperString==secondUpperString));
}
// -->
</script>
</head>
<body>
</body>
</html>
Use if statement with String.localeCompare
var oStringObject1 = new String("yellow");
var oStringObject2 = new String("brick");
var iResult = sTestString.localeCompare("brick");
if(iResult < 0) {
alert(oStringObject1 + "comes before "+ oStringObject2);
} else if (iResult > 0) {
alert(oStringObject1 + "comes after "+ oStringObject2);
} else {
alert("The two strings are equal");
}