javascript - 从仅出现一次的链接中查找完全匹配的字母
问题描述
我创建了一些代码来根据链接中找到的语言添加一些文本,但是由于模式太简单,我在完全匹配语言时遇到了问题。我需要准确找到 .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>
解决方案
您可以使用正则表达式/\.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>
推荐阅读
- node.js - Selenium - 如何确定点击值(findElement)?
- android - WebView 有时只加载
- javascript - 使用 Javascript 将 HTML 符号代码转换为实际符号
- linked-list - 寻找一种更有效的方法来创建一个 4 向链表
- flutter - Flutter websocket在一段时间后关闭
- visual-studio - CSPROJ 条件检测 Roslyn 的次要版本(或 VS IDE 的次要版本)
- javascript - 使用 mongodb 限制用户的投票
- arrays - 如何从 nd.array 区域获取特定值的平均值?
- android - 无法在 Android 上写入 NFC
- jquery - Magento 2:展开/折叠侧边栏菜单