如何替换两个字符内的所有出现。示例:
I love :octocat: beach and you do :joy: not like it
替换为将根据定界符内部生成的URL
生成的URLI love [img of octocat] beach and you do [img of joy] not like it
JavaScript需要捕获内部的内容:并替换
我尝试了几件事而没有成功。有人可以帮我吗?
幸运的是您的String.prototype.replace
接受Regexp和一个功能。因此,在您的示例中,您可以编写一条正则以找到2个字符之间的字符串并替换它们。
使用结肠的示例的示例正则是/:(.*?):/g
,您可以在功能中做任何您想做的事情,例如用字符串 附加字符替换字符串。例如
var str = "I love :octocat: beach and you do :joy: not like it"
str = str.replace(/:(.*?):/ig, function (str){
return str + 'BLAHBLAHBLAH'
})
str
的值现在是"I love :octocat:BLAHBLAHBLAH beach and you do :joy:BLAHBLAHBLAH not like it"
,有趣的东西eh?
使用String.replace
与回调函数查询地图{'pattern': 'replacement'}
:
let str = 'I love :octocat: beach and you do :joy: not like it';
let replacements = {
'octocat': '[img of octocat]',
'joy': '[img of joy]'
};
let result = str.replace(/:(w+):/g, (match, word) => replacements[word]);
console.log(result);
shrtfrm:
"I love :octocat: beach and you do :joy: not like it".split(":").map((el,i)=>i%2===0?el:{"octocat":"hello","joy":"test"}[el]||el).join("");
简单地拆分,更换并再次加入。
http://jsbin.com/moxexilica/edit?console
说明:
.split(":")
//returns: ["I love ","octocat"," beach and you do ","joy"," not like it"]
.map((el,i)=>i%2===0?el
//leave the strings outside (indexes 0,2,4) as they are
:el{"octocat":"hello","joy":"test"}[el]
//replace the others (indexes 1,3) with the value in the object so:
// octocat => hello
//joy => test
||el
//if it does not exist e. g. ':test:' fall back to 'test'
//now weve got:
//["I love ","hello"," beach and you do ","test"," not like it"]
.join("")
//a string
提取到功能:
function replace(str,replacer){
return str.split(":").map((el,i)=>i%2===0?el:replacer[el]||el).join("");
}
因此您可以做:
alert(replace("I love :octocat: beach and you do :joy: not like it", {octocat:"manly",joy:"not"}));
带有图像:
document.body.innerHTML=replace(document.body.innerHTML, {octocat:"<img src='octocat.png' />",joy:"<img src='joy.png' />"});
请注意,":"不是一个好的群众。您可能会使用更罕见的%%或!...