Home >Web Front-end >JS Tutorial >How to use localeCompare function

How to use localeCompare function

不言
不言Original
2019-02-18 11:39:015645browse

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.

How to use 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 = &#39;n&#39;.localeCompare(&#39;z&#39;); 
    document.write(a + &#39;<br>&#39;) 
  
    b = &#39;gfg&#39;.localeCompare(&#39;geeksforgeeks&#39;); 
    document.write(b + &#39;<br>&#39;) 
  
    c = &#39;a&#39;.localeCompare(&#39;a&#39;); 
    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 = [ &#39;go&#39;, &#39;php&#39;, &#39;css&#39;, &#39;How to use localeCompare function&#39; ]; 
    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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use min functionNext article:How to use min function