简体   繁体   中英

JavaScript Regex - Replace a custom tag inside a string

Lets say we have the following 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>

The result should look:

<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>

I know, I can do this with javascripts string replace function with regex, but not really how to do it. Basically something like this:

string.replace(/???/g, '<img src="$1" alt="$2" />');

But I can't find the right regex, since I am a regex newbie :(

{{ img\\((.*)\\) }} will find the img-code, but how to filter the attributes out?

I am writing a TinyMCE plugin which should work similar like the bb-code plugin, but with custom, non bb-code syntax.

You can use:

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>

You can use the following:

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);

This matching more towards your example should help to figure out the pattern that will work best for your needs.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM