且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有效地替换字符串中的所有重音字符?

更新时间:2023-12-03 20:30:53

我不能说你正在尝试用函数本身做什么,但如果你不喜欢正则表达式每次建立,这里有两个解决方案和一些警告每个。

I can't speak to what you are trying to do specifically with the function itself, but if you don't like the regex being built every time, here are two solutions and some caveats about each.

这是一种方法:

function makeSortString(s) {
  if(!makeSortString.translate_re) makeSortString.translate_re = /[öäüÖÄÜ]/g;
  var translate = {
    "ä": "a", "ö": "o", "ü": "u",
    "Ä": "A", "Ö": "O", "Ü": "U"   // probably more to come
  };
  return ( s.replace(makeSortString.translate_re, function(match) { 
    return translate[match]; 
  }) );
}

这显然会使正则表达式成为函数本身的属性。你唯一不喜欢这个(或者你可能,我猜它取决于)是正则表达式现在可以在函数体外修改。因此,有人可以这样做来修改通常使用的正则表达式:

This will obviously make the regex a property of the function itself. The only thing you may not like about this (or you may, I guess it depends) is that the regex can now be modified outside of the function's body. So, someone could do this to modify the interally-used regex:

makeSortString.translate_re = /[a-z]/g;

所以,有这个选项。

获得闭包的一种方法是防止有人修改正则表达式,将其定义为匿名函数赋值如下:

One way to get a closure, and thus prevent someone from modifying the regex, would be to define this as an anonymous function assignment like this:

var makeSortString = (function() {
  var translate_re = /[öäüÖÄÜ]/g;
  return function(s) {
    var translate = {
      "ä": "a", "ö": "o", "ü": "u",
      "Ä": "A", "Ö": "O", "Ü": "U"   // probably more to come
    };
    return ( s.replace(translate_re, function(match) { 
      return translate[match]; 
    }) );
  }
})();

希望这对你有用。

更新:现在还早,我不知道为什么我之前没有看到明显的情况,但是把你翻译也很有用闭包中的code>对象:

UPDATE: It's early and I don't know why I didn't see the obvious before, but it might also be useful to put you translate object in a closure as well:

var makeSortString = (function() {
  var translate_re = /[öäüÖÄÜ]/g;
  var translate = {
    "ä": "a", "ö": "o", "ü": "u",
    "Ä": "A", "Ö": "O", "Ü": "U"   // probably more to come
  };
  return function(s) {
    return ( s.replace(translate_re, function(match) { 
      return translate[match]; 
    }) );
  }
})();