Welcome to the Treehouse Community
Looking to learn something new?
How to check if string has same content
Hey. What is the best way to check if a string has the same content? so if its has it will do one thing, if its not, it will do something else. I know how to use if or else, but about the comparison itself. Is there a string method for this?
Tsenko Aleksiev3,819 Points
I'm not sure what exactly you want to do but I think that localCompare() method is the best choice. It returns -1 if the reference string is sorted before the compareString, 0 if are the same and 1 if the reference string is sorted after the compareString. Syntax: string.localeCompare(compareString)
var str1 = "cd"; var str2 = "ab"; var n = str1.localeCompare(str2); 1 // str1 is sorted after str2
Keep in mind that strings are compared in sort order and this methods depends on the language settings of the browser.
Barbara Szczygielska7,535 Points
var first = "a"; var second = "b"; var third = "a"; var fourth = "A"; first == second; // false first == third; // true first == fourth; // false first.toUpperCase() == fourth; // true
So if you want to compare the content, you should use toLowerCase or toUpperCase ;) (MDN toUpperCase)
I hope it helped, cheers! :)