Javascript slug函数与非拉丁字符

时间:2014-01-07 20:46:20

标签: javascript regex slug

我正在编写一个函数来输入slug。

var vslug = function (str) {
  str = str.replace(/^\s+|\s+$/g, '');
  str = str.toLowerCase();
  var vregex = /(?:\.([^.]+))?$/;
  var filename  = str.replace(vregex.exec(str)[0],'');
  var extension = vregex.exec(str)[1];
  var from = "àáäâèéëêìíïîıòóöôùúüûñçşğ·/,:;";
  var to   = "aaaaeeeeiiiiioooouuuuncsg_____";
  for (var i = 0; i < from.length; i++) {
    console.log('before ' + str);
    str = filename.replace(new RegExp(from[i], 'g'), to[i]);
    console.log('after ' + str);
  }
  str = str.replace(/[^a-z0-9 _-]/g, '')
  .replace(/\s+/g, '_')
  .replace(/-+/g, '_');
  if (typeof extension !== "undefined") {
    return str+'.'+extension;
  } else {
    return str;
  }
};

我无法成为这一部分 - 我失明了。任何帮助表示赞赏..

  var from = "àáäâèéëêìíïîıòóöôùúüûñçşğ·/,:;";
  var to   = "aaaaeeeeiiiiioooouuuuncsg_____";
  for (var i = 0; i < from.length; i++) {
    console.log('before ' + str);
    str = filename.replace(new RegExp(from[i], 'g'), to[i]);
    console.log('after ' + str);
  }

1 个答案:

答案 0 :(得分:2)

filename未更改 - 变量命名相同的字符串,并且不能修改字符串。因此,每个循环在使用filename.replace..时再次开始处理原始字符串。

相反,取消filename(或完全整合)并使用str = str.replace..

str = str.replace(vregex.exec(str)[0],'');
for (var i = 0; i < from.length; i++) {
  str = str.replace(new RegExp(from[i], 'g'), to[i]);
  // ^-- next loop gets new value
}

(另外,这可以用替换函数和映射而不是n循环来处理,并且可能有一个用于JavaScript的Unicode库...)


使用地图和替换功能的方法可能如下所示:

// Specify map somewhere reusable; can be built from paired arrays for simplicity.
var replacements = {"à":"a", "á":"a", .. ";":"_"}
// Object.keys is ES5, shim as needed. e.g. result: [à;á..]
var alternation = "[" + Object.keys(replacements).join("") + "]"
// This regex will match all characters we are trying to match.
var regex = new Regex(alternation, "g")

str = str.replace(regex, function (m) { 
    var r = replacements[m]
    return r || m        
})

请参阅String.replace(regex, function)