Development/JavaScript

javascript - url link 자동 인식(autoLink) 처리

linuxism 2014. 1. 8. 00:38


autolink-js

autolink-js is a small (about half a kilobyte), simple, and tested JavaScript tool that takes a string of text, finds URLs within it, and hyperlinks them.

Why bother releasing such a tiny little method?

I recently needed to find and hyperlink URLs in user-submitted text and was surprised to find that doing what seemed like such a simple task wasn't already a Solved Problem. Different regex solutions led to different unwanted side effects, and other utilities were far, far more complex and feature rich than I needed.

Basic Usage

autolink-js adds an autoLink() method to JavaScript's String prototype, so you can use it on any JavaScript string. Take a look at the tests, but essentially, after including either autolink.js or autolink-min.js to your page, it works like this:

// Input
"This is a link to Google http://google.com".autoLink()

// Output
"This is a link to Google <a href='http://google.com'>http://google.com</a>"

Additional Options

You can pass any additional HTML attributes to the anchor tag with a JavaScript object, like this:

// Input
"This is a link to Google http://google.com".autoLink({ target: "_blank", rel: "nofollow", id: "1" })

// Output
"This is a link to Google <a href='http://google.com' target='_blank' rel='nofollow' id='1'>http://google.com</a>"

Callback

Callback option can be used to redefine how links will be rendered.

// Input
"This is a link to image http://example.com/logo.png".autoLink({
  callback: function(url) {
    return /\.(gif|png|jpe?g)$/i.test(url) ? '<img src="' + url + '">' : null;
  }
});

// Output
"This is a link to image <img src='http://example.com/logo.png'>"

Example

Open example/example.html in your web browser and view the source for a simple but full-featured example of using with jQuery.

Running the tests

After cloning this repository, simply open test/suite.html in your web browser. The tests will run automatically.



출처 - https://github.com/bryanwoods/autolink-js





보통 많은 종류의 게시판에서 url형태나 email 형태에 자동 링크를 걸어주는 정규식을 사용하고 있습니다.. 좀전에 친구가 jsp로 게시판을 만드는 과정에서 자동링크를 할 수 있는 방법을 물어오길래 클라이언트에서 할 수 있는 방법을 생각해봤습니다. 자바는 1.4부터 RegExp 패키지를 사용할 수 있거든요...


생각해보니.. 서버측 부하는 적게 걸리면서 같은 효과를 낼 수 있을꺼 같아 팁으로 올립니다.


<html>

<body>

<script>

function autolink(id) {

        var container = document.getElementById(id);

        var doc = container.innerHTML;

        var regURL = new RegExp("(http|https|ftp|telnet|news|irc)://([-/.a-zA-Z0-9_~#%$?&=:200-377()]+)","gi");

        var regEmail = new RegExp("([xA1-xFEa-z0-9_-]+@[xA1-xFEa-z0-9-]+\.[a-z0-9-]+)","gi");

        container.innerHTML = doc.replace(regURL,"<a href='$1://$2' target='_blank'>$1://$2</a>").replace(regEmail,"<a href='mailto:$1'>$1</a>");

}

</script>

<div id="test">

폼체크 스크립트 lib.validate.js의 사용법은 http://maniacamp.com/examples/validate_howto.html 을 참조하세요<br>

거친마루의 이메일은 comfuture@studyfriend.net 입니다.<br>

php스쿨의 주소는 http://www.phpschool.com 입니다

</div>

<script>autolink('test');</script>

</body>

</html>


게시판등에 적용할때는 내용을 출력할 td에 id를 부여해주고 autolink('id'); 형태로 사용하면 되겠지요 : )

미리보기는 링크#1을 참조하세요


출처 - http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=14253&sca=&sfl=wr_subject&stx=%B8%B5%C5%A9&sop=and&page=4






function autoLink(content) {

    var regURL = new RegExp('(^|[^"])(http|https|ftp|telnet|news|irc)://([-/.a-zA-Z0-9_~#%$?&=:200-377()]+)', 'gi');

    var regURL2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;

    //var regEmail = new RegExp('([^:])([xA1-xFEa-z0-9_-]+@[xA1-xFEa-z0-9-]+\.[a-z0-9-]+\.[a-z0-9-]+)', 'gi');

    

    return content.replace(regURL, '$1<a class="autoLink" href="$2://$3" target="_blank">$2://$3</a>')

    .replace(regURL2, '$1<a class="autoLink" href="http://$2" target="_blank">$2</a>');

    //.replace(regEmail, '$1<a class="autoLink" href="mailto:$2">$2</a>');

}