JavaScript正则表达式-替换字符串中的自定义标记
假设我们有以下字符串:JavaScript正则表达式-替换字符串中的自定义标记,javascript,regex,Javascript,Regex,假设我们有以下字符串: <p>Hello, I am a cool string.</p> <p>Here I want to show an image: {{ img("path/to/file.jpg", "Title Text") }}</p> 你好,我是一个很酷的字符串 这里我想显示一个图像:{{img(“path/to/file.jpg”,“Title Text”)} 结果应该是: <p>Hello, I am a co
<p>Hello, I am a cool string.</p>
<p>Here I want to show an image: {{ img("path/to/file.jpg", "Title Text") }}</p>
你好,我是一个很酷的字符串
这里我想显示一个图像:{{img(“path/to/file.jpg”,“Title Text”)}
结果应该是:
<p>Hello, I am a cool string.</p>
<p>Here I want to show an image: <img src="path/to/file.jpg" alt="Title Text" /></p>
你好,我是一个很酷的字符串
这里我想展示一幅图像:
我知道,我可以用javascripts字符串替换函数和正则表达式来实现这一点,但实际上不知道如何实现。基本上是这样的:
string.replace(/???/g, '<img src="$1" alt="$2" />');
string.replace(/???/g');
但我找不到合适的正则表达式,因为我是正则表达式新手:(
{{img\(.*)}
将查找img代码,但是如何筛选属性呢
我正在编写一个TinyMCE插件,其工作原理应该与bb代码插件类似,但具有自定义的非bb代码语法。您可以使用:
var s = '<p>Here I want to show an image: {{ img("path/to/file.jpg", "Title Text") }}</p>';
var r = s.replace( /{{ img\( *"([^"]+)" *, *"([^"]+)" *\) *}}/g,
'<img src="$1" alt="$2" />' );
//=> <p>Here I want to show an image: <img src="path/to/file.jpg" alt="Title Text" /></p>
var s='这里我想显示一个图像:{{img(“path/to/file.jpg”,“Title Text”)};
var r=s.replace(/{img\(*”([^“]+)”*,*“([^“]+)”*\)*}/g,
'' );
//=>这里我想展示一幅图像:
您可以使用以下功能:
var str = '<img src="path/to/file.jpg" alt="Title Text" />';
var exp = /<.*img.*"(.*)".*"(.*)".*>/g;
var newStr = str.replace(exp,'<img src="$1" alt="$2" />');
console.log(newStr);
var-str='';
var exp=//g;
var newStr=str.replace(exp.);
console.log(newStr);
与您的示例进行更多的匹配将有助于找出最适合您需要的模式
var str2 = '<p>Here I want to show an image: {{ img("path/to/file.jpg", "Title Text") }}</p>';
var exp2 = /{{.*img.*"(.*)".*"(.*)".*}}/g;
var newStr2 = str2.replace(exp2,'<img src="$1" alt="$2" />');
console.log(newStr2);
var str2='这里我想显示一个图像:{{img(“path/to/file.jpg”,“Title Text”)};
var exp2=/{{.*img.*”(.*)“.*”(.*)”.}/g;
var newStr2=str2.replace(exp2',);
console.log(newStr2);
<>代码>你确信ReGEXES是这个工作的正确工具吗?如果你告诉我一个备选方案,我会很乐意使用它的。)。考虑使用例如KokOutjs或angurjs。你似乎想做模板。Eyegropram和anubhava的答案是正确的。顺便说一句,我需要一个类似于的tinymce插件,所以regex是choiceWorks的工具很棒,但我真的需要Separet”,因为我需要向url添加一些字符串,比如s.replace(/{img(*([^,]+),*([^)]+)*}/g、 “”);。我该怎么做呢?谢谢你们的努力!eyeprogram的速度快了一点,所以我选择了他的答案作为正确答案,但你们的答案也起作用了。OP总是决定选择最好的答案,但要快一些,你们确定吗?只需将鼠标悬停在两个答案上,你们就会看到我的答案比他快9分钟以上。我很瘦k你在帖子中犯了一个错误。我不想将标签替换为标签。你的代码不是我想要的,但我给了你+1,因为你的正则表达式帮助我找到了正确的答案。谢谢,也许这更接近你想要的?