我想用其他字符替换用户输入中的特殊字符。
当前,我有以下不起作用的内容。任何帮助将不胜感激。
$(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)*/
});
});
答案 0 :(得分:1)
您可以分割字符串(就像您已经在做但是没有空格一样),然后通过在特殊字符列表中找到map在每个字符上运行index。如果索引存在(返回值大于-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">
答案 1 :(得分:0)
不要被空格分开
$(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)*/
});
});
这意味着分割每个字符:
var splitInput = inputUser.split("");
答案 2 :(得分:0)
您可以尝试以下方法:
function cleanString(str) {
str = str.toLowerCase().replace(" ", "_");
str = str.replace(/[äâàáã]/g, "a").replace(/[ëêèéẽ]/g, "e").replace(/[ïîìíĩ]/g, "i");
str = str.replace(/[öôòóõ]/g, "o").replace(/[üûùúũ]/g, "u");
str = str.replace(/ç/g, "c").replace(/[^a-z0-9]/g, "");
return str;
}
测试
cleanString("áéíóú") // returns "aeiou"