gpt4 book ai didi

javascript - 交换 unicode 字符

转载 作者:行者123 更新时间:2023-12-03 07:47:31 27 4
gpt4 key购买 nike

我正在尝试编写一个函数,可以将字符串中的 unicode 字符替换为非 unicode ASCII 字符,问题是上传包含它们的字符串时,unicode 连字符和引号不会被读取。

我希望该函数有一个带有键值对的对象(以便可以使用更多的 unicode 引号或连字符进行更新,这可能会在将来引起问题),该对象的键是 ASCII 引号 "值是 unicode 引号的集合 交换出字符串。

    function replaceUnicode(string) {

var dictionary = {
'"': '"”"”',
'-': '-﹣'
}

}

我知道您可以使用正则表达式来交换字符串中的 unicode 字符,但我想使用此对象作为选定 unicode 字符的字典。我要问的是,如果您传入一个包含与字典的值匹配的 unicode 引号的字符串,您如何将这些引号交换为字典对象键值?

最佳答案

您可以使用字典,但仍然需要使用正则表达式进行替换才能找到匹配项。

这样的事情应该有效:

function replaceUnicode(s) {

var dictionary = {
'"': '"”"”',
'-': '-﹣'
}

for(var key in dictionary) {

var re = new RegExp(key,"g");
s = s.replace(re,dictionary[key])

}

return s

}


var str = 'hello "world" - how are - you';
console.log(replaceUnicode(str))

您可以在这里看到它的工作情况:https://jsfiddle.net/krpxu0gL/

希望有帮助!

关于javascript - 交换 unicode 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35140237/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com