【问题标题】:Vanilla JS - .replace() with array and loopVanilla JS - 带有数组和循环的 .replace()
【发布时间】:2022-01-18 14:20:57
【问题描述】:

我自己写了一个小脚本,可以将英语单词转换为精灵语单词。

var clickMe = document.querySelector('#button-7993f34d');

clickMe.addEventListener('click', function (event) {
  setTimeout(function() {
    var checkSelect = document.querySelector("select");
    // Lang
    checkSelect.innerHTML = checkSelect.innerHTML.replace('Tree', 'Adahl');
    checkSelect.innerHTML = checkSelect.innerHTML.replace('Forest', 'Adahlen');
    checkSelect.innerHTML = checkSelect.innerHTML.replace('Arrow', 'Assan');
  }, 0);
});
<select>
  <option>Tree</option>
  <option>Forest</option>
  <option>Arrow</option>
</select>
<button id="button-7993f34d">click me</button>

一切正常。但是,我想以数组的形式呈现单词。例如:

langs = [
  {"eng": "Tree", "elf": "Adahl"},
  {"eng": "Forest", "elf": "Adahlen"},
  {"eng": "Arrow", "elf": "Assan"}
]

不再重复:

 checkSelect.innerHTML = checkSelect.innerHTML.replace('Tree', 'Adahl');

此线程最接近我的解决方案: Using replace string method inside forEach 但是,我无法使其适应我的脚本。

在我的情况下可能吗?我试图用替换功能找到类似的解决方案。不幸的是,无济于事。能给点建议吗?

不过,我一直在努力,如果我在回答之前找到了解决方案,我一定会分享。

【问题讨论】:

  • “但是,我无法使其适应我的脚本。” - 尝试在哪里? -> minimal reproducible example
  • 为什么langs 是一个对象数组,每个单词一个对象?为什么不使用 { &lt;english word&gt;: &lt;elvish word&gt; } -> { "Tree": "Adahl", "Forest": "Adahlen", ... } 的单个对象? -> Object.entries()
  • 替换innerHTML是个坏主意,它会做很多内部工作,并且可能导致数据丢失。您应该考虑将元素文本拆分为 textNodes,并仅覆盖 textNodes 的文本内容。
  • 要不要使用一个专门的国际化工具,比如i18next?这是一种适用于小型网站和大型项目的多功能工具。

标签: javascript arrays replace lang


【解决方案1】:

这是一个非常基本的功能,可以用精灵术语替换出现的英语术语。

function replaceText(text) {
  const langs = [
    {"eng": "Tree", "elf": "Adahl"},
    {"eng": "Forest", "elf": "Adahlen"},
    {"eng": "Arrow", "elf": "Assan"}
  ];
  let textToReturn = text;
  langs.forEach((word) => {
    textToReturn = textToReturn.replaceAll(word.eng, word.elf);
  });
  return textToReturn;
};

console.log(replaceText("My Tree is in the Forest")); 

【讨论】:

【解决方案2】:

您也可以使用 switch 语句来做到这一点。

switch(wordInEnglish) {

    case "Tree": return "Adahl";
    
    case "Forrest": return "Adahlen";

    case "Arrow": return "Assan";

}

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 2018-03-15
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多