Search This Blog

Thursday, 28 July 2016

How to compare the two given string using javascript?

Html page:

<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

JavaScript page:

<script>
function myFunction()
{
    var str1 = "ab";
    var str2 = "cd";
    var n = str1.localeCompare(str2);
    document.getElementById("demo").innerHTML = n;
}
</script>

Output:
-1

·         Returns -1 if str1 is sorted before str2
·         Returns 0 if the two strings are equal

·         Returns 1 if str1 is sorted after str2

No comments:

Post a Comment