首页 > 解决方案 > 从仅出现一次的链接中查找完全匹配的字母

问题描述

我创建了一些代码来根据链接中找到的语言添加一些文本,但是由于模式太简单,我在完全匹配语言时遇到了问题。我需要准确找到 .com 之后的内容,仅此而已。我试过这个/.*\/\/.*?\/(\S{2})/gm表达,但它不是我要找的。

//find the url of the page
// const findUrl = window.location.href;
const findUrl = "https://www.example.com/fr/Pages/examplefr.html";
console.log(findUrl);

const langs = [{
    pattern: /en/, //find strictly only the EN
    text: "A very long text in English to replace existing text"
  },
  {
    pattern: /fr/, //find strictly only the FR
    text: "Je ne parle pas français"
  },
  {
    pattern: /es/, //find strictly only the ES
    text: "No hablo español."
  }
];

let found = false;
for (let i = 0; i < langs.length; i++) {
  if (findUrl.match(langs[i].pattern)) {
    console.log("The match has been found!");
    let findP = document.getElementById("texts").querySelectorAll("p");
    findP[0].innerText = langs[i].text;
    found = true;
    break;
  }
}
if (!found) {
  console.log("The match was not found");
}
<div id="texts">
 <p>Some text here</p>
</div>

标签: javascriptregex

解决方案


您可以使用正则表达式/\.com\/(\w{2})\//来获取语言并将其作为文本进行比较。langs如果您的对象是格式,这会更容易{[lang: string]: string}

const findUrl = "https://www.example.com/fr/Pages/examplefr.html";
console.log(findUrl);

const langs = {
  "en": "A very long text in English to replace existing text",
  "fr": "Je ne parle pas français",
  "es": "ANo hablo español.",
};

if (!findLanguage()) console.log("The match was not found");

function findLanguage() {
  var result = /\.com\/(\w{2})\//.exec(findUrl);
  if (result && result[1] in langs) {
    console.log("The match has been found!");
    document.querySelector("#texts p").textContent = langs[result[1]];
    return true;
  }
}
<div id="texts">
  <p>Some text here</p>
</div>


推荐阅读