在 JavaScript 中删除字符串中的重音符号/变音符号

编程入门 行业动态 更新时间:2024-10-28 11:34:18
本文介绍了在 JavaScript 中删除字符串中的重音符号/变音符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何从字符串中删除重音字符?特别是在 IE6 中,我有这样的事情:

How do I remove accentuated characters from a string? Especially in IE6, I had something like this:

accentsTidy = function(s){ var r=s.toLowerCase(); r = r.replace(new RegExp(/s/g),""); r = r.replace(new RegExp(/[àáâãäå]/g),"a"); r = r.replace(new RegExp(/æ/g),"ae"); r = r.replace(new RegExp(/ç/g),"c"); r = r.replace(new RegExp(/[èéêë]/g),"e"); r = r.replace(new RegExp(/[ìíîï]/g),"i"); r = r.replace(new RegExp(/ñ/g),"n"); r = r.replace(new RegExp(/[òóôõö]/g),"o"); r = r.replace(new RegExp(/œ/g),"oe"); r = r.replace(new RegExp(/[ùúûü]/g),"u"); r = r.replace(new RegExp(/[ýÿ]/g),"y"); r = r.replace(new RegExp(/W/g),""); return r; };

但是 IE6 给我带来了麻烦,似乎它不喜欢我的正则表达式.

but IE6 bugs me, seems it doesn't like my regular expression.

推荐答案

使用 ES2015/ES6 String.prototype.normalize(),

With ES2015/ES6 String.prototype.normalize(),

const str = "Crème Brulée" str.normalize("NFD").replace(/[u0300-u036f]/g, "") > "Creme Brulee"

这里发生了两件事:

  • normalize()ing to NFD Unicode 范式将组合字形分解为简单字形的组合.Crème 的 è 最终表示为 e + ̀.
  • 使用正则表达式 字符类 匹配 U+0300 → U+036F 范围,现在可以轻松地在全球范围内删除变音符号,Unicode 标准将其方便地分组为 组合变音符号 Unicode 块.
  • normalize()ing to NFD Unicode normal form decomposes combined graphemes into the combination of simple ones. The è of Crème ends up expressed as e + ̀.
  • Using a regex character class to match the U+0300 → U+036F range, it is now trivial to globally get rid of the diacritics, which the Unicode standard conveniently groups as the Combining Diacritical Marks Unicode block.
  • 从 2021 年开始,您还可以使用 Unicode 属性转义:

    As of 2021, one can also use Unicode property escapes:

    str.normalize("NFD").replace(/p{Diacritic}/gu, "")

    性能测试见评论.

    或者,如果您只想排序

    Intl.Collat​​or 有足够的支持~95% 现在,polyfill 也可用 这里 但我还没有测试过.

    Intl.Collator has sufficient support ~95% right now, a polyfill is also available here but I haven't tested it.

    const c = new Intl.Collator(); ["creme brulee", "crème brulée", "crame brulai", "crome brouillé", "creme brulay", "creme brulfé", "creme bruléa"].sort(cpare) ["crame brulai", "creme brulay", "creme bruléa", "creme brulee", "crème brulée", "creme brulfé", "crome brouillé"] ["creme brulee", "crème brulée", "crame brulai", "crome brouillé"].sort((a,b) => a>b) ["crame brulai", "creme brulee", "crome brouillé", "crème brulée"]

    更多推荐

    在 JavaScript 中删除字符串中的重音符号/变音符号

    本文发布于:2023-10-26 22:58:26,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1531594.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:符号   重音   字符串   JavaScript

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!