How to check a given string is an anagram of another string in JavaScript ?
Anagram: An anagram is a word or sentence, which usually contains all the original letters exactly once, in order to arrange the letters of a different term or phrase. Some of the examples are given below:
- evil = vile
- a gentleman = elegant man
- eleven plus two = twelve plus one
Example 1: In this article, we will use in-built functions such as split(), sort(), and join() to check if a given string is an anagram of another string in JavaScript.
HTML
< script > function checkAnagram(a, b) { // Not of same length, can't be Anagram if (a.length !== b.length) { return false; } // Inbuilt functions to rearrange the string var str1 = a.split('').sort().join(''); var str2 = b.split('').sort().join(''); var result = (str1 === str2); return result; } // Checking the output console.log(checkAnagram('abc', 'cba')); </ script > |
Output:
true
Example 2: In this article, we will the javascript for loop to check if a given string is an anagram of another string in JavaScript.
HTML
< script > function checkAnagram(a, b) { var array = {}; if (a === b) { return true; } if (a.length !== b.length) { return false; } for (let i = 0; i < a.length ; i++) { let res = a .charCodeAt(i) - 97; array[res] = (array[res] || 0) + 1; } for (let j = 0 ; j < b.length; j++) { let res = b .charCodeAt(j) - 97; if (!array[res]) { return false; } array[res]--; } return true; } console.log(checkAnagram('abc', 'cba')); </script> |
Output:
true
Please Login to comment...