我有以下Array
的strings
:
array = [
"My Website | :PrismicReplace|title"
"My Website | Contact Us"
];
我想遍历这些数组,并且如果元素包含
:PrismicReplace
,我想在管道之后提取值,这样字符串中的:PrismicReplace|title
将返回title
作为键...即
>> my_function("My Website | :PrismicReplace|title")
title
该字符串可以是:
"My Website | :PrismicReplace|someReallyReallyReallyLongParameter"
(返回someReallyReallyReallyLongParameter)
要么
"My Website | :PrismicReplace|someReallyReallyReallyLongParameter Some Other Stuff"
(仍然返回someReallyReallyReallyLongParameter)
我已经尝试过将循环和正则表达式匹配在一起使用,但是它还没有达到我的预期效果……但是我在想并希望有一个快速的解决方案?到目前为止,我最好的是:
if (new RegExp(':PrismicReplace').test(tagDef.content)) {
for (const [key, value] of Object.entries(prismic)) {
let paramRegex = new RegExp(`:PrismicReplace|${key}`);
if (paramRegex.test(tagDef.content)) {
tagDef.content = tagDef.content.replace(paramRegex, prismic[key]);
}
}
}
最佳答案
您可以在管道后的零件上使用带有捕获组的图案。
:PrismicReplace\|([^\s|]+)
在部分
:PrismicReplace\|
匹配:PrismicReplace|
(
捕获组1[^\s|]+
匹配1个以上出现的任何char,但不包括管道或空白char)
关闭第1组Regex demo
let array = [
"My Website | :PrismicReplace|title",
"My Website | Contact Us",
"My Website | :PrismicReplace|someReallyReallyReallyLongParameter",
"My Website | :PrismicReplace|someReallyReallyReallyLongParameter Some Other Stuff"
];
const regex = /:PrismicReplace\|([^\s|]+)/g;
array.forEach(str => {
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
console.log(m[1]);
}
});