Skip to content

How to compare two strings character by character in JavaScript | Example

  • by

Using the while loop with the splice and indexof method you can compare two strings character by character in JavaScript.

Compare two strings character by character in JavaScript

Simple example code using a while loop to get Compare of two strings.

<!DOCTYPE html>
<html>
<body>
  <script>
   var str1 = "ansar@#//1";
   var str2 = "@#//sanra123";

   s1 = str1.split('');

   s2 = str2.split('');


   var i = s1.length + 1;
   while (i--) {
    if (s2.indexOf(s1[i]) >= 0)
      s2.splice(s2.indexOf(s1[i]), 1);
  }

  console.log(s2)

</script>
</body>
</html> 

Output:

How to compare two strings character by character in JavaScript

Find the difference between two strings in JavaScript

function getDifference(a, b)
    {
        var i = 0;
        var j = 0;
        var result = "";

        while (j < b.length)
        {
         if (a[i] != b[j] || i == a.length)
             result += b[j];
         else
             i++;
         j++;
        }
        return result;
    }
    console.log(getDifference("lebronjames", "lebronnjames"));

Output: n

Do comment if you have any doubts or suggestions on this Js string topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading