您现在的位置: 万盛学电脑网 >> 程序编程 >> 脚本专题 >> javascript >> 正文

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

作者:佚名    责任编辑:admin    更新时间:2022-06-22

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

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

  语法

  ?

1 string.localeCompare( param )

  下面是参数的详细信息:

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

  返回值:

  0 : 字符串匹配100%

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

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

  例子:

  ?

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

  这将产生以下结果:

  ?

1 2 localeCompare first :-1 localeCompare second :1