August 17, 2024
JavaScript String Compare
Comparison of two strings in JavaScript is very easy task. Like integer values you can also compare string objects with the help of equal to operator (==) inside of if conditional statement. It is as easy as you are comparing two values. The example of string comparison mentioned below:
Code
<html>
<head>
<title>JavaScript String Compare</title>
<script language='JavaScript' type='text/Javascript'>
function compare_two_string(str1, str2){
if(str1 == str2) {
alert('Strings are equal');
return true;
} else {
alert('Strings are not equal');
return false;
}
}
</script>
</head>
<body>
<form name='myform'>
<input type='text' name='txtstr1' id='txtstr1'>
<input type='text' name='txtstr2' id='txtstr2'>
<input type='button' name='myBtn' id='myBtn' value='Compare'
onclick='compare_two_string( document.getElementById( "txtstr1" ).value ,
document.getElementById( "txtstr2" ).value);'>
</form>
</body>
</html>
In above mentioned example, we have created a form which has two text boxes and a button. We have also created a function with the name of 'compare_two_string' which required two string parameters for comparison. We called this function on onCkick event of 'Compare String' button. compare_two_string function compare two string if strings are found equal then it shows an alert with message 'strings are equal' and returns true value. And if strings are not equal then it returns another alert with message that 'String are not equal.' and returns false.