首页 > 语言 > JavaScript > 正文

JavaScript中操作字符串之localeCompare()方法的使用

2024-05-06 16:21:35
字体:
来源:转载
供稿:网友

这篇文章主要介绍了JavaScript中操作字符串之localeCompare()方法的使用,是JS入门学习中的基础知识,需要的朋友可以参考下

这个方法返回一个数字表示参考字符串是否到来之前或之后或相同的排序顺序给定的字符串。

语法

 

 
  1. string.localeCompare( param ) 

下面是参数的详细信息:

param : 字符串对象进行比较的字符串

返回值:

0 : 字符串匹配100%

1 : 不匹配,参数值来自于语言环境的排序顺序字符串对象的值之前

-1 : 不匹配,参数值来自于语言环境的排序顺序字符串对象的值之后

例子:

 

 
  1. <html> 
  2. <head> 
  3. <title>JavaScript String localeCompare() Method</title> 
  4. </head> 
  5. <body> 
  6. <script type="text/javascript"
  7. var str1 = new String( "This is beautiful string" ); 
  8. var index = str1.localeCompare( "XYZ" ); 
  9. document.write("localeCompare first :" + index );  
  10.  
  11. document.write("<br />" );  
  12.  
  13. var index = str1.localeCompare( "AbCD ?" ); 
  14. document.write("localeCompare second :" + index );  
  15.  
  16. </script> 
  17. </body> 
  18. </html> 

这将产生以下结果:

 

 
  1. localeCompare first :-1 
  2. localeCompare second :1  

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选