inputArray = ["z","d"];
inputArray = ["د","ذ"];
function trans(stri){
inputArray.forEach((value, i) => {
var next = i + 1;
a1 = inputArray[i];
a2 = outputArray[i];
regex = new XRegExp(a1, "g");
stri = XRegExp.replace(stri, regex, a2, ["all"])
return stri;
});
}
console.log(trans("dzzd"))我想把拉丁字符翻译成阿拉伯字符,如何使用{阿拉伯}}?,而我对RegExp甚至XRegExp非常陌生,那么我基本上是怎么做的呢?另外,如果我缺乏经验,我也很抱歉。
预期产出= "دذذد“
发布于 2022-08-28 05:29:05
您可以在一次传递中完成所有替换,对inputArray进行替换,并使用替换函数在匹配时从outputArray返回适当的字符:
function trans(str, from, to) {
return str.replace(new RegExp(`${from.join('|')}`, 'g'), function(m) {
return to[from.indexOf(m)];
});
}
inputArray = ["z", "d"];
outputArray = ["ذ", "د"];
console.log(trans('dzzd', inputArray, outputArray))
请注意,如果from可能包含重叠值(例如,ab和a),则需要在使用它们之前根据from中字符串的长度对from和to进行排序。您可以使用以下代码来完成这一任务:
// create an array of indexes
ids = Array.from({length : from.length}, (_, i) => i)
// sort the indexes by the length of the corresponding string in `from`
ids.sort((a, b) => from[b].length - from[a].length)
// now map from and to to the new order
from = from.map((_, i) => from[ids[i]])
to = to.map((_, i) => to[ids[i]])这确保正则表达式总是按照首选项匹配最长的序列(因为它将在交替中排在第一位)。
您可以插入到trans函数中,例如:
function trans(str, from, to) {
ids = Array.from({ length: from.length }, (_, i) => i)
ids.sort((a, b) => from[b].length - from[a].length)
from = from.map((_, i) => from[ids[i]])
to = to.map((_, i) => to[ids[i]])
return str.replace(new RegExp(`${from.join('|')}`, 'g'), function(m) {
return to[from.indexOf(m)];
});
}
inputArray = ["zz", "d"];
outputArray = ["ذ", "د"];
console.log(trans('dzzd', inputArray, outputArray))
或者在调用inputArray和outputArray之前在trans上使用
function trans(str, from, to) {
return str.replace(new RegExp(`${from.join('|')}`, 'g'), function(m) {
return to[from.indexOf(m)];
});
}
inputArray = ["zz", "d"];
outputArray = ["ذ", "د"];
ids = Array.from({ length: inputArray.length }, (_, i) => i)
ids.sort((a, b) => inputArray[b].length - inputArray[a].length)
inputArray = inputArray.map((_, i) => inputArray[ids[i]])
outputArray = outputArray.map((_, i) => outputArray[ids[i]])
console.log(trans('dzzd', inputArray, outputArray))
https://stackoverflow.com/questions/73516102
复制相似问题