如何替换两个字符内的所有匹配项。 示例:
I love :octocat: beach and you do :joy: not like it
替换为将根据分隔符内的内容生成的网址
I love [img of octocat] beach and you do [img of joy] not like it
Javascript需要捕获内部的内容:并替换
我尝试过几件事但没有成功。有人可以帮助我吗?
答案 0 :(得分:2)
幸运的是你String.prototype.replace
接受了一个RegExp和一个函数。因此,在您的示例中,您可以编写一个正则表达式来查找2个字符之间的字符串并替换它们。
使用冒号的示例的RegEx只是/:(.*?):/g
,您可以在函数中执行任何操作,例如用字符串+附加字符替换字符串。 e.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"
,有趣的东西嗯?
答案 1 :(得分:1)
使用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);
答案 2 :(得分:0)
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' />"});
请注意,“:”不是一个好的删除者。您可能会使用更为罕见的%%或!! ...