1

フォーラムがあり、いくつかの主要なリンクを自動的に解析したいと考えています。たとえば、ユーザーが次のような投稿をしたとします。

StackOverflow にアクセスしてください。ウィキペディアで見つけました。

次のように自動的に解析します。

<a href="http://stackoverflow.com">StackOverflow</a> にアクセスしてください。<a href="http://en.wikipedia.org/wiki/">ウィキペディア</a>で見つけました。

これは JavaScript のみを使用しても実行できますか?

助けてくれてありがとう。:-)

4

4 に答える 4

1

クリーンで拡張可能なコードを作成したいのは、word => linkのライブラリを作成することです。その後、それを繰り返して、コード内で置換を行うことができます。

これは、 http://jsfiddle.net/MjV84/を実行するフィドルデモです。

$(function() {

    var text = $('#foo').text(),
        library = {
            stackoverflow: 'http://stackoverflow.com',
            wikipedia: 'http://wikipedia.com'
        },
        name;

    for (name in library) {
        text = text.replace(new RegExp(name, 'gi'), function(word) {
            return '<a href="' + library[name] + '">'+word+'</a>';
        });  
    };

    $('#foo ').html(text);
});​
于 2012-04-25T17:07:53.873 に答える
1

テキストを前処理している場合は、代替を使用してコールバックreplaceと正規表現で関数を使用できます。

var str = "You should visit StackOverflow. I found it on Wikipedia.";
str = str.replace(/StackOverflow|Wikipedia|etc/gi, function(m) {
    var href;
    switch (m.toLowerCase()) {
        case "stackoverflow";
            href = "http://stackoverflow.com";
            break;
        case "wikipedia";
            href = "http://en.wikipedia.org";
            break;
        // ...and so on...
    }
    return '<a href="' + href + '">' + m + '</a>';
});

YMMD は、上記では各キーワードを 2 回定義する必要があると指摘していますが、これは事実です。多数のキーワードを使用してこれを行う必要があった場合、キーワードをキーとして、href値を値としてオブジェクトを作成し、式を動的に作成しました。

// ==== Setup code you presumably do once

// The substitutions -- make sure the keys are in lower case
var substitutions = {
    "stackoverflow": "http://stackoverflow.com",
    "wikipedia":     "http://en.wikipedia.org",
    // ...and so on...
};

// Build the regex. Here I've used `Object.keys` which is an ES5 feature
// but you can use an ES5 shim (since it's something a shim can provide).
// Note that if your keywords include any special regular expression
// characters, you'll have to loop through the keys manually and escape
// those.
var subrex = new RegExp(Object.keys(substitutions).join("|"), "gi");

// ==== Where you're using it
var str = "You should visit StackOverflow. I found it on Wikipedia.";
str = str.replace(subrex, function(m) {
    return '<a href="' + substitutions[m.toLowerCase()] + '">' + m + '</a>';
});

実例| ソース

于 2012-04-25T16:53:27.280 に答える
1

はい、それを行うには String.replace(regex, replaceString) を使用してください。

次に例を示します。

var text = "You should visit StackOverflow. I found it on Wikipedia.";

var newText=text.replace(/stackoverflow/gi,
                         "<a href='http://www.stackoverflow.com/'>StackOverflow</a>");

gグローバルを表すため、すべてのインスタンスを置き換え、iは大文字と小文字を区別しない検索を意味します。

「辞書」などの一般的な単語をリンクするdictionary.comために置き換える場合は、ユーザーが特別なタグを追加した場合にのみ置き換えたほうがよいでしょう。次に例を示します。

"You should visit StackOverflow. I found it on Wikipedia."

次のように書かれていない限り、リンクに置き換えるべきではありません。

"You should visit &StackOverflow. I found it on Wikipedia."

次に、メソッドは特別なシンボルを追加するだけで済みます。

また、次のような配列にデータを配置します。

var linkArray = [ ["StackOverflow", "http://www.stackoverflow.com/", "Description"],
                  ["Wikipedia", "http://wikipedia.org/", "Free encyclopedia"] ];

次に、インスタンスを見つけて置き換えるループを作成します。

function addLinks(textInput) {
    for (var i=0; i<linkArray.length; i++) {
        textInput = addLink(textInput, linkArray[i]);
    }
    return textInput;
}

function addLink(textInput, link) {
    var replaceString = "<a href=\"" + link[1] + "\" title=\""
                      + link[2] + "\">"
                      + link[0] + "</a>";
    return textInput.replace(new RegExp("&"+link[0], "gi"), replaceString);
}
于 2012-04-25T16:54:05.223 に答える
0

ターゲット文字列に大文字と小文字が異なる置換文字列のバリアントが含まれている場合、正規表現で i 修飾子を使用した以前のすべての回答は失敗します。これは、ターゲット文字列の部分文字列が置換属性名と一致しないためです。

このバージョンでは、各置換文字列をキャプチャし、見つかった文字列の引数配列を検索することでこれを解決します。

function substitute (str) { 'use strict';
  var substitutions = {
        "Stack Overflow": "http://stackoverflow.com",
        "Wikipedia":     "http://en.wikipedia.org",
        // ...and so on...
      },
      skeys = Object.keys (substitutions);

  // build regexp which will capture each match separtely
  return str.replace (new RegExp ('(' + skeys.join(")|(") + ')', "gi"), function (m0) {
    // Now scan the arguments array (omitting the last two arugments which
    // are the source string and match index)
    for (var ai, i = arguments.length - 2; --i;) {
      // The index of the argument (less 1) corresponds to the index in skeys of
      // the name in the substitutions  
      if ((ai = arguments[i])) {
        return '<a href="' + substitutions[skeys[i - 1]] + '">' + ai + '</a>';
      }
    }    
    return m0;    
  });
}


var str = "You should visit stack overflow. I found it on Wikipedia."; 

// check in console log that links are correctly built.
console.log (substitute (str));
document.write (substitute (str));

jsfiddle を参照してください: http://jsfiddle.net/NmGGN/

于 2012-04-25T17:58:09.930 に答える