我使用 php,现在我需要用 js 做一些事情。(我是用 php 做的)
我有字符串:constentence =“{{GALLERY_slider_8}} Lorem ipsum dolor sat amet。”;
我想用函数替换 {{GALLERY_slider_8}} 。
const newString = sentence.replace(/({{2})([A-Z]+)(_{1})(.*)(_{1})(.*)(}{2})/g, function(match, p1, p2, p3, p4, p5, p6, p7, offset, string) {
if (p2 === "GALLERY"){
return`This is gallery images from the ${p4} folder!`;
}else if(p2 === "NUMBERS"){
return`This is my numbers!`;
}
});
console.log(newString);
一切都按预期工作,在控制台中我看到了这一点
//这是我的滑块文件夹中的图库图像! Lorem ipsum dolor 坐 amet
但是如果我的字符串是这样的:
常量句=“{{GALLERY_slider_8}} Lorem ipsum dolor sat amet {{NUMBERS__}}”;
我想用两个单独的函数替换 {{GALLERY_slider_8}} 和 {{NUMBERS__}}。
在控制台中我看到这个:
//这是我来自 slider_8 的图库图片}} Lorem ipsum dolor sat amet {{NUMBERS_ 文件夹!
所以模式没有按预期工作!
请帮忙寻找多次更换的解决方案。
您可以尝试使用以下正则表达式:
{{([A-Z]+)_(.*?)}}
const sentence = "{{GALLERY_slider_8}} Lorem ipsum dolor sit amet {{NUMBERS__}}";
const newString = sentence.replace(/{{([A-Z]+)_(.*?)}}/g, function(match, p1, p2, offset, string) {
if (p1 === "GALLERY") {
return `This is gallery images from the ${p2} folder!`;
} else if (p1 === "NUMBERS") {
return `This is my numbers!`;
}
});
console.log(newString);