首页 > 解决方案 > 替换字符串数组中的字符

问题描述

我想用其他字符替换用户输入的特殊字符。

目前,我有以下不起作用。任何帮助,将不胜感激。

$(document).ready(function(){ 
        $("#text_box_id").change(function () {
            /*var name = $(this).val();
            var dname_without_space = $("#text_box_id").val().replace(/ /g, "");*/

            var specialCharList = ["Á","É","Í","Ó","Ú","á","é","í","ó","ú","ñ","Ñ"];
            var replaceChar = ["A","E","I","O","U","a","e","i","o","u","n","N"];

            var inputUser = $("#text_box_id").val();
            var splitInput = inputUser.split(" ");
            console.log(splitInput);

            for(var i = 0; i < inputUser.length; i++){
                for(var x = 0; x < specialCharList.length; x++){
                    if(splitInput[i] == specialCharList[x]){
                        splitInput[i] = replaceChar[x];
                    }
                }
            }

            var modInputUser = splitInput.join(" ");
            console.log(modInputUser);

            /*var name_without_special_char = $("#text_box_id").val().replace(/[^a-zA-Z 0-9]+/g, ""); 
            $(this).val(name_without_special_char);
            console.log(name_without_special_char)*/
        });
    });

标签: javascriptjquery

解决方案


您可以拆分字符串(就像您已经在做但没有空格一样),然后通过在特殊字符列表中查找索引来对每个字符运行映射。如果索引存在(返回值大于),那么您可以使用该索引从替换字符列表中获取值。-1

然后它看起来像这样:

$(document).ready(function() {
  $("#text_box_id").change(function() {

    let specialCharList = ["Á", "É", "Í", "Ó", "Ú", "á", "é", "í", "ó", "ú", "ñ", "Ñ"];
    let replaceChar     = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u", "n", "N"];

    let inputUser = $("#text_box_id").val();

    let newString = inputUser.split('').map(i => {
      let idx = specialCharList.indexOf(i)
      return idx > -1 ? replaceChar[idx] : i
    }).join('')

    $("#text_box_id").val(newString)
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text_box_id">


推荐阅读