14

私は次の配列を持っています:

emoticons = {
   ':-)' : 'smile1.gif',
   ':)'  : 'smile2.gif',
   ':D'  : 'smile3.gif'     
}

それから私はテキストで変数を持っています。

var text = 'this is a simple test :)';

およびWebサイトのURLを持つ変数

var url = "http://www.domain.com/";

シンボルを画像に置き換える関数を作成するにはどうすればよいですか?

<img>タグの結果は次のようになります。

<img src="http://www.domain.com/simple2.gif" />

(URL変数を画像の名前に連結する必要があります)。

どうもありがとうございます!

4

3 に答える 3

33

別のアプローチ:

function replaceEmoticons(text) {
  var emoticons = {
    ':-)' : 'smile1.gif',
    ':)'  : 'smile2.gif',
    ':D'  : 'smile3.gif'
  }, url = "http://www.domain.com/";
  // a simple regex to match the characters used in the emoticons
  return text.replace(/[:\-)D]+/g, function (match) {
    return typeof emoticons[match] != 'undefined' ?
           '<img src="'+url+emoticons[match]+'"/>' :
           match;
  });
}

replaceEmoticons('this is a simple test :)');
// "this is a simple test <img src="http://www.domain.com/smile2.gif"/>"

編集: @pepkin88emoticonsは、オブジェクトのプロパティ名に基づいて正規表現を作成するという非常に良い提案をしました。

これは簡単に実行できますが、これを適切に機能させるには、メタ文字をエスケープする必要があります。

エスケープされたパターンは配列に格納され、基本的にメタ文字RegExpで区切られたすべてのパターンを結合することにより、後でコンストラクターを使用して正規表現を構築するために使用されます。|

function replaceEmoticons(text) {
  var emoticons = {
    ':-)' : 'smile1.gif',
    ':)'  : 'smile2.gif',
    ':D'  : 'smile3.gif',
    ':-|'  : 'smile4.gif'
  }, url = "http://www.domain.com/", patterns = [],
     metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;

  // build a regex pattern for each defined property
  for (var i in emoticons) {
    if (emoticons.hasOwnProperty(i)){ // escape metacharacters
      patterns.push('('+i.replace(metachars, "\\$&")+')');
    }
  }

  // build the regular expression and replace
  return text.replace(new RegExp(patterns.join('|'),'g'), function (match) {
    return typeof emoticons[match] != 'undefined' ?
           '<img src="'+url+emoticons[match]+'"/>' :
           match;
  });
}

replaceEmoticons('this is a simple test :-) :-| :D :)');
于 2010-06-16T17:09:37.050 に答える
4
for ( smile in emoticons )
{
   text = text.replace(smile, '<img src="' + url + emoticons[smile] + '" />');
}
于 2010-06-16T17:07:06.363 に答える
0

検索置換要素の配列で正規表現を使用すると、うまく機能します。

var emotes = [
    [':\\\)', 'happy.png'],
    [':\\\(', 'sad.png']
];

function applyEmotesFormat(body){
    for(var i = 0; i < emotes.length; i++){
        body = body.replace(new RegExp(emotes[i][0], 'gi'), '<img src="emotes/' + emotes[i][1] + '">');
    }
    return body;
}
于 2010-09-10T19:46:46.860 に答える