用javascript替换重音字符

时间:2017-08-29 18:00:47

标签: javascript non-ascii-characters

on onkeyup,我想将重音字符替换为非重音符号。现在有了这个代码,我什么都没得到。如果我没有将this.value提供给函数,我会收到split的错误。

我想用onkeyup来使用这个函数获取更多输入,但总是为那个输入,我写的是什么。

<input onKeyUp="RemoveAccents(this.value);" type="text" required name="termek_seo" class="product-name" value="<?php echo isset($_POST["termek_seo"])?$_POST["termek_seo"]:""; ?>" />



    function RemoveAccents(strAccents) 
{
    var strAccents = strAccents.split('');
    var strAccentsOut = new Array();
    var strAccentsLen = strAccents.length;
    var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
    var accentsOut = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
    for (var y = 0; y < strAccentsLen; y++) 
    {
        if (accents.indexOf(strAccents[y]) != -1) 
        {
            strAccentsOut[y] = accentsOut.substr(accents.indexOf(strAccents[y]), 1);
        }
        else
        {
            strAccentsOut[y] = strAccents[y];
        }
    }
    strAccentsOut = strAccentsOut.join('');
    return strAccentsOut;
}

更新

我如何在此代码中编写tolowercase?

function RemoveAccents(s) 
{
    var i = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖŐòóôõöőÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜŰùúûüűÑñŠšŸÿýŽž'.split('');
    var o = 'AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUUuuuuuNnSsYyyZz'.split('');
    var map = {};
    i.forEach(function(el, idx) {map[el] = o[idx]});
    return s.replace(/[^A-Za-z0-9]/g, function(ch) { return map[ch] || ch; })
}

2 个答案:

答案 0 :(得分:1)

我用另一个代码解决了这个问题:

function RemoveAccents(s) 
{
    var i = 'ĂĂĂĂĂĂà åâãäüĂĂĂĂĂĂĹòóôþÜĹĂĂĂĂèÊêÍðĂçĂĂĂĂĂĂŹĂ­ĂŽĂŻĂĂĂĂŰÚúÝߏĂùŠťŸÿýŽŞ+_.:;[]()/*"<> '.split('');
    var o = 'AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUUuuuuuNnSsYyyZz---------------'.split('');
    var map = {};
    i.forEach(function(el, idx) {map[el] = o[idx]});
    return s.replace(/[^A-Za-z0-9]/g, function(ch) { return map[ch] || ch; }).toLowerCase();
}

答案 1 :(得分:0)

它只是有效......

function RemoveAccents(strAccents) {
  var strAccents = strAccents.split('');
  var strAccentsOut = new Array();
  var strAccentsLen = strAccents.length;
  var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
  var accentsOut = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
  for (var y = 0; y < strAccentsLen; y++) {
    if (accents.indexOf(strAccents[y]) != -1) {
      strAccentsOut[y] = accentsOut.substr(accents.indexOf(strAccents[y]), 1);
    } else {
      strAccentsOut[y] = strAccents[y];
    }
  }
  strAccentsOut = strAccentsOut.join('');
  console.log(strAccentsOut);
  return strAccentsOut;
}
<input onKeyUp="RemoveAccents(this.value);" type="text" required name="termek_seo" class="product-name" value="ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž" />