check if two strings are anagrams
built-in functions
[ regex | replace | split | sort | join | length | toLowerCase ]

Check if two strings are anagrams of each other

Write a function to check if two strings are anagrams of each other, returning true if they are anagrams, otherwise returns false.

Only alphanumeric characters will be considered and any whitespace or special characters or case will be ignored.


Anagrams

An anagram is a word or phrase formed by rearranging the letters of another word or phrase, typically using all the original letters exactly once. An anagram does not have to have the same meaning as the original word or phrase.


Example ...

Enter 2 strings ...

"Silent" string1

"listen" string2

The function will return true, both strings are anagrams of each other.

Both strings have the same length and the exact same letters appear exactly once, case is ignored.

The function will return false if both strings are not anagrams of each other.

Strings are a sequence of zero or more characters written inside quotes used to represent text.

Strings may consist of letters, numbers, symbols, words, or sentences.

Strings are immutable, they cannot be changed.

Each character in a string has an index.

The first character will be index 0 the second character will be index 1 and so on.

There are two ways to access an individual character in a string.

charAt() method

const str1 = "abc"; string

str1.charAt(0); character at index 0 → "a"

str1.charAt(1); character at index 1 → "b"

str1.charAt(2); character at index 2 → "c"

str1.charAt(3); character at index 3 → "" index not found

Alternatively use at() or slice() methods

bracket notation []

const str2 = "abc"; string

str2[0]; character at index 0 → "a"

str2[1]; character at index 1 → "b"

str2[2]; character at index 2 → "c"

str2[3]; character at index 3 → undefined index not found


Arrays are used to store multiple values in a single variable.

Each value is called an element, and each element has a numeric position in the array, known as its index.

Arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.

Arrays can contain any data type, including numbers, strings, and objects.

const arr1 = [2, 4, 6]; array

arr1[0]; element at index 0 → 2

arr1[1]; element at index 1 → 4

arr1[2]; element at index 2 → 6

arr1[3]; element at index 3 → undefined index not found


Check if two strings are anagrams using built-in functions ↴.

replace() method → returns a new string with the value(s) replaced.

Regular Expression → patterns used to match character combinations in strings.

toLowerCase() method → returns the value of the string converted to lower case.

split() method → splits a string into an array of substrings.

sort() method → sorts the elements of an array in place and returns the reference to the same array, now sorted.

join() method → returns an array as a string.

length property → return the length of a string.


replace() method searches a string for a value or a regular expression and returns a new string with the value replaced.

If pattern is a string, only the first occurrence will be replaced. The original string is unchanged.

syntax

string.replace(pattern, replacement)

const str3 = "hello world";

str3.replace("hello", "HELLO"); replace "hello" with "HELLO"

returns ↴

"HELLO world"

const str4 = "ABCDEF";

str4.replace("B", ""); replace "B" with "" empty string

returns ↴

"ACDEF""B" removed from string


Regular expressions are patterns used to match character combinations in strings.

The Regular Expression /[^a-z0-9]/gi; matches the first letter of each word.

^ caret symbol beginning of a character class negates the set, meaning it matches any character not listed.

[^a-z0-9] character class matches any character that is not a lower case letter a to z or a digit 0 to 9

g flag indicates that the search should be global, meaning it will find all occurrences.

i flag makes the search case-insensitive, allowing it to match both upper case and lower case characters.


toLowerCase() method converts all letters to lower case. The original string is unchanged.

const str5 = "hELlo wORLd";

str5.toLowerCase(); returns ↴

"hello world" → lower case


split() method splits a string into an array of substrings based on a specified separator (delimiter). The original string is unchanged.

("") separator → string is split between each character.

(" ") separator → string is split at each space character, resulting in an array of words.

const str6 = "Hello"; → string

str6.split(""); returns ↴

["H", "e", "l", "l", "o"] → array

const str7 = "hello world"; → string

str7.split(" "); returns ↴

["hello", "world"] → array


sort() method sorts the elements of an array as strings.

By default, the elements of the array are converted to strings and sorted in ascending order by comparing their sequences based on their UTF-16 code unit values.

sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.

sort() method is stable, it preserves the order of items in an array when their values are the same.

sort() method can sort an array of numbers, strings, or objects with custom functions.

syntax

array.sort()

Sort in ascending order

const arr2 = ["c", "a", "e", "b", "d"];

arr2.sort(); returns ↴

["a", "b", "c", "d", "e"]

console.log(arr2); returns ↴

["a", "b", "c", "d", "e"] → original array mutated


join() method joins all elements of an array into a single string with a specified separator between each element. The original array is unchanged.

("") separator → returns a string joined with no spaces between each character.

(" ") separator → returns string joined with a single space between each element.

const arr3 = ["H", "e", "l", "l", "o"]; array

arr3.join(""); returns ↴

"Hello" → string

const arr4 = ["Hello", "World"]; array

arr4.join(" "); returns ↴

"Hello World" → string


Chaining these 3 built-in functions together ↴

const str8 = "caebd"; string to be sorted

str8.split("").sort().join(""); returns ↴

"abcde" → string


length property returns the number of characters in a string.

const str9 = "Hello World";

str9.length; returns ↴

11 → there are 11 characters in the string


Initialize a variable to hold the first string to compare.

const string1 = "silent"; → user input

Initialize a variable to hold the second string to compare.

const string2 = "listen"; → user input


Define a function isAnagram() to check if two strings are anagrams.

function isAnagram(str1, str2) {}

The function removes all non-alphanumeric characters and converts all characters to lower case.

If the strings have the same length, they are split into an array of characters, sorted alphabetically, and joined back into a string.

If both strings are anagrams, their sorted versions will be identical.

The function takes two strings str1, str2 and checks if the two strings are anagrams.

If both strings are anagrams of each other, return true, otherwise return false. The original strings remains unchanged.

Remove non-alphanumeric characters and convert all characters to lower case.

str1 = str1.replace(/[^a-z0-9]/gi, "").toLowerCase() str1

str2 = str2.replace(/[^a-z0-9]/gi, "").toLowerCase() str2

Check if the lengths of the cleaned strings are equal.

if (str1.length !== str2.length) {}

If length of each string is different they cannot be anagrams.

return false false end execution of function

If both strings have the same length,

split each string into an array, sort, and join back into a string.

str1 = str1.split("").sort().join("")

str2 = str2.split("").sort().join("")

Compare the sorted strings and return the result.

If both strings are identical they must be anagrams.

return str1 === str2 true anagram found

Return false If strings are not identical.

If the function returns true, strings are anagrams of each other

If the function returns false, strings are not anagrams of each other


Call the function with ↴

isAnagram(string1, string2);


Check if two strings are anagrams.

const string1 = "silent";

const string2 = "listen";

function isAnagram(str1, str2) {

str1 = str1.replace(/[^a-z0-9]/gi, "").toLowerCase();

str2 = str2.replace(/[^a-z0-9]/gi, "").toLowerCase();

if (str1.length !== str2.length) {

return false;

}

str1 = str1.split("").sort().join("");

str2 = str2.split("").sort().join("");

return str1 === str2;

}

call function

isAnagram(string1, string2); returns ↴

true


Anagram examples ↴

eleven plus two = twelve plus one

The Morse code = Here come dots

Vacation time = I am not active

Schoolmaster = The classroom

A gentleman = Elegant man

Astronomer = Moon starer

debit card = bad credit

iceman = cinema

silent = listen

Check if two strings are anagrams of each other