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

编程入门 行业动态 更新时间:2024-10-28 13:27:28
本文介绍了在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()转到 NFD Unicode普通表单将合并的字形分解为简单的组合。 Crème的è最终表示为 e + 。
  • 使用正则表达式字符类以匹配U + 0300→U + 036F范围,它现在是微不足道的 g 自由地摆脱变音符号,其中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.
  • 查看性能测试评论。

    或者,如果您只想要排序

    Intl.Collat​​or 有足够的支持约85%现在,一个polyfill也可以这里但我还没有测试过。

    Intl.Collator has sufficient support ~85% 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:11,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1531593.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:符号   重音   字符串   JavaScript

    发布评论

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

    >www.elefans.com

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