2017-11-28 2 views
0

チャットアプリでは、URLを投稿して自動的にハイパーリンクさせることができます。だから、例えばメッセージ:ハイパーリンクとスマイリーを表示するための文字列の書式設定

Hi there! use http://google.com/ to search for things!

がにフォーマットされます:

私の知る限りは(どこかstackoverflowのから)見つけたとしてあまりにもハードではないHi there! use <a href='http://google.com/'>http://google.com/</a> to search for things!

です以下:

function addHyperlinks(str) { 
    // Set the regex string 
    var regex = /(https?:\/\/([-\w\-\.]+)+(:\d+)?(\/([\w\-\/_\.]*(\?\S+)?)?)?)/ig 
    // Replace plain text links by hyperlinks 
    var replaced_text = str.replace(regex, "<a href='$1' target='_blank'>$1</a>"); 
    // Echo link 
    return replaced_text; 
} 

これは動作しているようです。しかし、私はあまりにもイメージとスマイリーを交換したいので、ユーザの投稿の場合:

Hi there! use http://google.com/ to search for things! :D

がにフォーマットされます:

Hi there! use <a href='http://google.com/'>http://google.com/</a> to search for things! <img src='/grin.gif' />

どのように私はこれを行うことができますか?彼らは彼らが両方ともコロンを持っているので、私はそれを動作させるためにどちらかを選ぶことができるようにする必要があるようです、そして顔文字:/は問題を作成します。

答えて

0

多分このように1つずつマッピングすることで顔文字を置き換えることができます。

function replaceEmoticonToImageSrc(text) { 
var siteUrl = 'http://www.yoursite.com/' 
var emoticons = { 
    ':D' : 'emoticongif.gif', 
    ':)' : 'emoticon2gif.gif', 
    }; 
    return text.replace(/[:\-)D]+/g, function (match) { 
    return typeof emoticons[match] != 'undefined' ? 
      '<img src="' + siteUrl + emoticons[match] + '"/>' : 
      match; 
    }); 
} 
関連する問題