toLocaleLowerCase()和toLowerCase()之间的区别

98

我在尝试使用FiddletoLocaleLowerCase()以及toLowerCase()方法。

function ByLocale() {
  document.getElementById("demo").innerText.toLocaleLowerCase();
}

function ByLower() {
  document.getElementById("demo").innerText.toLowerCase();
}
<p>Click the button to convert the string "HELLO World!" to lowercase letters.</p>

  <button onclick="ByLocale();">By Locale LowerCase</button>
  <button onclick="ByLower();">By LowerCase</button>

<p id="demo">HELLO World!</p>

我的问题是:

  • 什么是Locale,因为这两个函数似乎返回类似的输出?
  • 这两种方法之间有什么区别?
  • 为什么fiddle代码没有被执行?

https://dev59.com/HXVC5IYBdhLWcg3w4Vb6#155257 - Silly Volley
1个回答

80
与 `toLowerCase` 不同,`toLocaleLowerCase` 考虑了本地化因素。在大多数情况下,对于大多数语言,它们会产生类似的输出,但某些语言的行为可能不同。 请查看 MDN 上的描述: 引用: “`toLocaleLowerCase()` 方法根据任何特定于语言环境的大小写映射将字符串的值转换为小写。`toLocaleLowerCase()` 不会影响字符串本身的值。在大多数情况下,这将产生与 `toLowerCase()` 相同的结果,但对于某些语言环境(例如土耳其语),它们的大小写映射不遵循 Unicode 中的默认大小写映射,可能会得到不同的结果。”
为了完整起见,`toUpperCase` 和 `toLocaleUpperCase` 的行为类似,只是进行大写处理。

现在来解决你的代码片段没有任何作用的问题。实际上有两个问题。

  1. 这些方法返回新的字符串,不会修改原始字符串(JavaScript 字符串是不可变的)。你需要将值重新赋给元素。

  2. innerText 是非标准的,在所有浏览器上都不起作用。请改用 textContent,只有在支持旧版本 IE 的情况下才添加 innerText 更新: innerText 现在已经标准化,尽管在回答发布时还没有。

有效的代码片段:

const demo = document.getElementById('demo');
const str = demo.textContent;

function toLowerCase() {
  demo.textContent = str.toLowerCase();
}

function toLocaleLowerCase() {
  demo.textContent = str.toLocaleLowerCase();
}

function toLocaleLowerCaseDe() {
  demo.textContent = str.toLocaleLowerCase('de-DE');
}

function toUpperCase() {
  demo.textContent = str.toUpperCase();
}

function toLocaleUpperCase() {
  demo.textContent = str.toLocaleUpperCase();
}

function toLocaleUpperCaseDe() {
  demo.textContent = str.toLocaleUpperCase('de-DE');
}

function reset() {
  demo.textContent = str;
}
<p>Click the buttons to apply each function to the string below.</p>

<button onclick="toLowerCase();">toLowerCase</button>
<button onclick="toLocaleLowerCase();">toLocaleLowerCase</button>
<button onclick="toLocaleLowerCaseDe();">toLocaleLowerCase("de-DE")</button>
<br><br>
<button onclick="toUpperCase();">toUpperCase</button>
<button onclick="toLocaleUpperCase();">toLocaleUpperCase</button>
<button onclick="toLocaleUpperCaseDe();">toLocaleUpperCase("de-DE")</button>
<br><br>
<button onclick="reset();">reset</button>

<p id="demo">WELCOME TO THE WORLD FÊTE! In HAUPTSTRAßE, İstanbul.</p>


1
@学生,稍等一下,我会添加那个的。 - Alexander O'Mara
5
用英语时,这两种方法会得到相同的输出。我猜在像法语这样的语言中,这很相关,因为在瑞士大写字母没有重音,而在法国则有惯例。 - Everts
1
@学生 添加了一个带有解释的可工作代码片段。 - Alexander O'Mara
11
@AlexanderO'Mara,你应该添加一个“土耳其语”作为演示差异的例子;-) - Legends
1
在代码中添加了更多的示例。我理解的是,在en-EN区域设置中,所有“Locale”函数的结果都与“非Locale”函数的结果相同。如果有人能找到一个反例,请在这里评论和/或将其添加到代码中。 - undefined
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接