[英]JavaScript Regex - Replace a custom tag inside a string
可以說我們有以下字符串:
<p>Hello, I am a cool string.</p>
<p>Here I want to show an image: {{ img("path/to/file.jpg", "Title Text") }}</p>
結果應如下所示:
<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>
我知道,我可以使用regex的javascripts字符串替換功能來做到這一點,但實際上並非如此。 基本上是這樣的:
string.replace(/???/g, '<img src="$1" alt="$2" />');
但是我找不到合適的正則表達式,因為我是正則表達式新手:(
{{ img\\((.*)\\) }}
將找到img代碼,但是如何將屬性過濾掉呢?
我正在編寫一個TinyMCE插件,該插件的工作方式應類似於bb-code插件,但具有自定義的非bb-code語法。
您可以使用:
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 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 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.