2023年1月13日 星期五

JavaScript text to hyperlink 和 自動換行

nl2br() 函數在字符串中的每個新行(\n) 之前插入HTML 換行符(<br />)。 


function nl2br (str, is_xhtml) {

    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br ' + '/>' : '<br>';

    var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/=\/_\.]*(\?\S+)?)?)?)/ig

    var str = str.replace(regex, "<a href='$1' target='_blank'>$1</a>");

    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');

}

沒有留言:

張貼留言