Javascript html text filter / linkify

I am trying to parse HTML code for links, the idea is to replace image links with <img> and other links with <a> .

I am basically looking for something like this:

https://github.com/dejan/jquery-auto_html/blob/master/jquery.auto_html.js

But it works with both HTML and text. Meaning: It should replace http://google.com , but not <a href="http://google.com">google</a>

Can I do this without visible functions in regex? Thanks.

We must move from

 html = "Here is a great site: http://google.com!" convert(html) > "Here is a great site: <a href=\"http://google.com\">google</a>!" html = "Here is a great site: <a href=\"http://google.com\">google</a>!" convert(html) > "Here is a great site: <a href=\"http://google.com\">google</a>!" 
+4
source share
1 answer

The following regular expression replacements will replace links to <a> and image links to <img> elements. It excludes links that are already inside href=" or src=" etc.

 function replaceStuff(html) { return html .replace(/[^\"]http(.*)\.(png|jpg|jpeg|gif)/g, ' <img src="http$1.$2">' .replace(/[^\"]http(.*)\.([a-zA-Z]*)/g, ' <a href="http$1.$2">http$1.$2</a>') ); } 

You can call it like this:

 // will replace the link to <a> replaceStuff('Hello http://google.com'); // will not replace anything replaceStuff('Hello <a href="http://google.com">ff</a>'); // will replace image link to <img> replaceStuff('Hello http://google.com/image.png'); // will not replace anything replaceStuff('Hello <img src="http://google.com/image.png">'); 
+2
source

Source: https://habr.com/ru/post/1387968/


All Articles