简体   繁体   English

如何用数组中的 2 个字符串替换 1 个字符串?

[英]How to replace 1 string with 2 strings in an array?

Here's an example:这是一个例子:

I have this array:我有这个数组:

const chars = [ "ä", "t", "i" ]

and I'd like to achieve this outcome:我想实现这个结果:

const chars = ["a", "e", "t", "i" ]

Basically, I'd like to replace some special chars:基本上,我想替换一些特殊字符:

  • ä -> a, e ä -> a, e
  • ü -> u, e ü -> 你, e
  • ö -> o, e ö -> o, e

I've been trying to use a switch function like this:我一直在尝试像这样使用开关 function:

    const charsArray = ["ä", "t", "i"]
    const replaceChars = (char) => {
          switch (char) {
            case "ä":
              return ("a", "e");
            default:
              return char;
          }
        };
    const cleanArray = charsArray.map((c) => {return replaceChars(c)}
    //output: ["e", "t", "i"] instead of: ["a","e", "t", "i"]

The problem: it only returns 1 value, so f.ex.问题:它只返回 1 个值,所以 f.ex。 for "ä" it only returns "e".对于“ä”,它只返回“e”。

Any help is appreciated!任何帮助表示赞赏! Thanks!谢谢!

you need to return array from function and use flatMap to combine it together:您需要从 function 返回数组并使用flatMap将其组合在一起:

 const charsArray = ["ä", "t", "i"] const replaceChars = (char) => { switch (char) { case "ä": return ["a", "e"]; default: return char; } }; const cleanArray = charsArray.flatMap((c) => replaceChars(c)); console.log(cleanArray);

you can join it into a string and then use the String.replace() method (and then split it into an array again):您可以将其加入字符串,然后使用 String.replace() 方法(然后再次将其拆分为数组):

 const charsArray = ["ä", "t", "i", "ü"]; const cleanArray = charsArray.join("").replace(/ä/g, "ae").replace(/ü/g, "ue") // you can chain as many.replace() methods as you want here.split(""); console.log(cleanArray);

Immediate answer: at case "ä": return ["a", "e"];立即回答:在case "ä": return ["a", "e"];

But this is not efficient, you might want to use a Map that gives you instant access.但这效率不高,您可能需要使用Map来让您即时访问。

 console.clear(); const chars = new Map(); chars.set("ä", "ae"); chars.set("ö", "oe"); const text = ["ä", "t", "i", "ö"]; const res = text.map(x => chars.get(x) || x).flatMap(x => x.split('')); console.log(res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM