Home >Web Front-end >JS Tutorial >How to use localeCompare function
localeCompare() is a built-in function in How to use localeCompare function that can be used to compare any two elements in a specific order. Let's take a quick look at the specific usage of the localeCompare function.
Let’s first take a look at the basic syntax of the localeCompare function
stringObject.localeCompare(target)
Explanation: If stringObject is less than target, localeCompare() returns A number less than 0. If stringObject is greater than target, this method returns a number greater than 0. If the two strings are equal, or there is no difference according to local collation, this method returns 0.
Let’s look at specific examples
The code is as follows
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> a = 'n'.localeCompare('z'); document.write(a + '<br>') b = 'gfg'.localeCompare('geeksforgeeks'); document.write(b + '<br>') c = 'a'.localeCompare('a'); document.write(c) </script> </body> </html>
The output results are as follows
-1 1 0
The localeCompare function can also sort elements
The code is as follows
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var elements = [ 'go', 'php', 'css', 'How to use localeCompare function' ]; a = elements.sort((a, b) => a.localeCompare(b)); document.write(a) </script> </body> </html>
The output result is as follows:
css,go,How to use localeCompare function,php
This article ends here. For more exciting content, you can pay attention to other related articles on the php Chinese website Column tutorial! ! !
The above is the detailed content of How to use localeCompare function. For more information, please follow other related articles on the PHP Chinese website!