将JavaScript字符串全部转换为小写吗?

时间:2020-03-06 14:56:47  来源:igfitidea点击:

如何将JavaScript字符串值转换为所有小写字母?

示例:从"姓名"到"姓名"

解决方案

是的,JavaScript中的任何字符串都有一个toLowerCase()方法,该方法将返回一个新的字符串,该字符串在所有小写形式中都是旧字符串。旧字符串将保持不变。

因此,我们可以执行以下操作:

"Foo".toLowerCase();
document.getElementById('myField').value.toLowerCase();

var lowerCaseName = "Your Name".toLowerCase();

使用String对象的toLowerCase或者toLocaleLowerCase方法。区别在于toLocaleLowerCase将考虑用户/主机的当前语言环境。根据ECMAScript语言规范(ECMA-262)的15.5.4.17,toLocaleLowerCase

…works exactly the same as toLowerCase
  except that its result is intended to
  yield the correct result for the host
  environment’s current locale, rather
  than a locale-independent result.
  There will only be a difference in the
  few cases (such as Turkish) where the
  rules for that language conflict with
  the regular Unicode case mappings.

例子:

var lower = 'Your Name'.toLowerCase();

还要注意,toLowerCasetoLocaleLowerCase函数被实现为可在任何值类型上通用。因此,即使在非String对象上,我们也可以调用这些函数。这样做将意味着在更改结果字符串值中每个字符的大小写之前,将自动转换为字符串值。例如,我们可以在类似这样的日期直接应用" toLowerCase":

var lower = String.prototype.toLowerCase.apply(new Date());

实际上等效于:

var lower = new Date().toString().toLowerCase();

由于其简单性和可读性,通常优选第二种形式。在较早版本的IE上,第一个具有的好处是它可以与" null"值一起使用。在null'上应用toLowerCase或者toLocaleLowerCase的结果将产生null`(而不是错误条件)。

toLocaleUpperCase()或者小写的函数的行为不正常。

例如,在我的系统Safari 4,Chrome 4 Beta,Firefox 3.5.x中,它错误地转换了带有土耳其字符的字符串。

浏览器分别对navigator.language响应为" en-US"," tr"和" en-US"。

但是,据我所知,没有办法在浏览器中获得用户的Accept-Lang设置。

尽管我已将每个浏览器都配置为首选tr-TR语言环境,但只有Chrome才给我带来麻烦。

我认为这些设置只会影响HTTP标头,但我们无法通过JS访问这些设置。

在Mozilla文档中,它说:"在遵守当前语言环境的同时,字符串中的字符会转换为...。

对于大多数语言,这将返回与..."相同的结果。

我认为这对土耳其语有效,它与配置为en或者tr并无区别。

在土耳其语中,应将" D?N?"转换为到"丁?"和" DIN?"到" d?n?"或者相反亦然。

例子

<script type="text/javascript">
var yourstring = 'Your Name'
var lowercase = yourstring.toLowerCase();
document.write('original string:<b> ' + yourstring + '</b><br>');
document.write('converted sting <b>' + lowercase + '</b>');
</script>

试试

http://htmledit.squarefree.com/